Display image with base64 String in html?

base64, html, image, java

Solution

This: `String str = itStrm.toString()` is not the image but the `toString()` representation of the `FileInputStream` instance.

You'll have to read the bytes from the stream and store them in a byte array. And, for performance reasons, buffer the stream:

BufferedInputStream itStrm = new BufferedInputStream(FileInputStream(
    "E:\\image\\56255254-flower.jpg"));

Further reading (Spoiler: solution inside)

- Convert InputStream to byte array in Java

Problem

here is my java code that construct the base64 String from image. Then place the base64 String html, to view the constructed image, but image is not constructed somehow ``` public void getBase64String() throws FileNotFoundException { FileInputStream itStrm = new FileInputStream( "E:\\image\\56255254-flower.jpg");//image is lying at http://danny.oz.au/travel/mongolia/p/56255254-flower.jpg String str = itStrm.toString(); byte[] b3 = str.getBytes(); String base64String = new sun.misc.BASE64Encoder().encode(b3); //output of base64String is amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA== } ``` Now in html page i placed the output of base64String in img tag to view the image.But image does not shows up (instead it display the cross image icon). I am not getting image is not displayed from base64 String below? ``` <HTML> <BODY> <img src="data:image/jpeg;base64,amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA=="/> </BODY> </HTML> ``` EDIT:- Thanks Folks, i used byte[] bytes = IOUtils.toByteArray(is);. It worked for me!!

Original source

Related problems