将 byte[] 转换为 Base64 字符串以获取数据 URI [英] Convert byte[] to Base64 string for data URI
问题描述
我知道这可能已被问到 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();
这篇关于将 byte[] 转换为 Base64 字符串以获取数据 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!