简体   繁体   English

用html中的base64字符串显示图像?

[英]Display image with base64 String in html?

here is my java code that construct the base64 String from image. 这是我从图像构造base64字符串的java代码。 Then place the base64 String html, to view the constructed image, but image is not constructed somehow 然后放置base64 String html,以查看构造的图像,但不以某种方式构建图像

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). 现在在html页面中我将base64String的输出放在img标签中以查看图像。但是没有显示图像(而是显示交叉图像图标)。 I am not getting image is not displayed from base64 String below? 我没有从base64字符串下面显示图像?

      <HTML>
      <BODY>
           <img    src="data:image/jpeg;base64,amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA=="/>

     </BODY>
     </HTML>

EDIT:- Thanks Folks, i used byte[] bytes = IOUtils.toByteArray(is);. 编辑: -谢谢Folks,我使用byte [] bytes = IOUtils.toByteArray(is);. It worked for me!! 它对我有用!!

This: String str = itStrm.toString() is not the image but the toString() representation of the FileInputStream instance. 这: String str = itStrm.toString()不是图像,而是FileInputStream实例的toString()表示。

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) 进一步阅读(Spoiler:解决方案内部)

You would need to use the read() method of the FileInputStream instance instead of the toString() to get the content of the image. 您需要使用FileInputStream实例的read()方法而不是toString()来获取图像的内容。 Then you are able to encode it and should work as you expected. 然后你就可以对它进行编码,并且应该按预期工作。

Something like: 就像是:

int c;
StringBuffer result = new StringBuffer("");
while((c = fileInputStream.read()) != -1)
{
    result .append((char)c);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM