将 byte[] 转换为数据 URI 的 Base64 字符串
我知道这可能已经被问了 10000 次,但是,我似乎无法找到这个问题的直接答案.
I know this has probably been asked 10000 times, however, I can't seem to find a straight answer to the question.
我的数据库中存储了一个代表图像的 LOB;我从数据库中获取该图像,我想通过 HTML IMG 标记在网页上显示它.这不是我的首选解决方案,但在我找到更好的解决方案之前,这是一个权宜之计.
I have a LOB stored in my db that represents an image; I am getting that image from the DB and I would like to show it on a web page via the HTML IMG tag. This isn't my preferred solution, but it's a stop-gap implementation until I can find a better solution.
我正在尝试通过以下方式使用 Apache Commons Codec 将 byte[] 转换为 Base64:
I'm trying to convert the byte[] to Base64 using the Apache Commons Codec in the following way:
String base64String = Base64.encodeBase64String({my byte[]});
然后,我试图在我的页面上显示我的图像,如下所示:
Then, I am trying to show my image on my page like this:
<img src="data:image/jpg;base64,{base64String from above}"/>
它显示的是浏览器默认的我找不到这个图片",图片.
It's displaying the browser's default "I cannot find this image", image.
有人有什么想法吗?
谢谢.
推荐答案
我使用了这个并且效果很好(与接受的答案相反,它使用了不推荐用于这种情况的格式):
I used this and it worked fine (contrary to the accepted answer, which uses a format not recommended for this scenario):
StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
contourChart = sb.toString();
相关文章