java 在 html 中显示带有 base64 字符串的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13024243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display image with base64 String in html?
提问by M Sach
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
这是我的java代码,它从图像构造base64字符串。然后放置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). I am not getting image is not displayed from base64 String below?
现在在 html 页面中,我将 base64String 的输出放在 img 标签中以查看图像。但图像不显示(而是显示十字图像图标)。我没有从下面的 base64 字符串中获取图像未显示?
<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!!
编辑:-谢谢大家,我使用了 byte[] bytes = IOUtils.toByteArray(is);。它对我有用!!
回答by Andreas Dolk
This: String str = itStrm.toString()
is not the image but the toString()
representation of the FileInputStream
instance.
这:String str = itStrm.toString()
不是图像,而是实例的toString()
表示FileInputStream
。
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)
进一步阅读(剧透:里面的解决方案)
回答by dasheddot
You would need to use the read()
method of the FileInputStream
instance instead of the toString()
to get the content of the image. Then you are able to encode it and should work as you expected.
您需要使用实例的read()
方法FileInputStream
而不是toString()
来获取图像的内容。然后您就可以对其进行编码,并且应该可以按预期工作。
Something like:
就像是:
int c;
StringBuffer result = new StringBuffer("");
while((c = fileInputStream.read()) != -1)
{
result .append((char)c);
}