将字节[]转换为数据URI的Base64字符串
我知道这可能已被问过10000次,但是,我似乎无法找到问题的直接答案。将字节[]转换为数据URI的Base64字符串
我有一个LOB存储在我的数据库中,代表一个图像;我从数据库中获取该图像,并且希望通过HTML IMG标记将其显示在网页上。这不是我首选的解决方案,但是,除非我能找到更好的解决方案,否则这是一个阶段性的实施。
我试图使用Apache共享编解码器以下列方式为字节[]转换为Base64:
String base64String = Base64.encodeBase64String({my byte[]});
然后,我想表明我的网页这样对我的形象:
<img src="data:image/jpg;base64,{base64String from above}"/>
它显示浏览器的默认“我找不到这个图像”,图像。
有没有人有任何想法?
谢谢。
我用这个和它工作得很好(违背了公认的答案,它使用不推荐使用此方案的格式):
StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
contourChart = sb.toString();
根据官方文档Base64.encodeBase64URLSafeString(byte[] binaryData)
应该是你在找什么。
此外,JPG的MIME类型是image/jpeg
。
[*文章中的PNG例子](https://secure.wikimedia.org/wikipedia/en/ wiki/Data_URI_scheme#示例)表明使用+和/是可以的。 – 2011-01-29 18:07:05
有没有人真的试过使用Base64.encodeBase64URLSafeString()的输出来查看它是否在浏览器中工作? encodeBase64URLSafeString()似乎不会生成有效/标准的base64编码。 要使base64编码的字符串符合URI,应该对其应用标准URI字符转义。我不认为上述功能是你想要的。 – Keeth 2013-08-14 17:28:11
这个答案实际上并没有为我生成适当的字符串。 Hugo的答案包含缺失的编码以使其正常工作。 – ryber 2013-12-12 22:30:03
这是正确的语法。这可能是因为您的Web浏览器不支持数据URI方案。请参阅Which browsers support data URIs and since which version?
此外,JPEG MIME类型是image/jpeg
。
您可能还想考虑将图像流式传输到浏览器,而不是将其编码到页面本身。
这里是通过servlet,它可以很容易地采用流式传输BLOB的内容,而不是文件输出到浏览器的流媒体文件中包含的图像的一个例子:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
ServletOutputStream sos = resp.getOutputStream();
try {
final String someImageName = req.getParameter(someKey);
// encode the image path and write the resulting path to the response
File imgFile = new File(someImageName);
writeResponse(resp, sos, imgFile);
}
catch (URISyntaxException e) {
throw new ServletException(e);
}
finally {
sos.close();
}
}
private void writeResponse(HttpServletResponse resp, OutputStream out, File file)
throws URISyntaxException, FileNotFoundException, IOException
{
// Get the MIME type of the file
String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
if (mimeType == null) {
log.warn("Could not get MIME type of file: " + file.getAbsolutePath());
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mimeType);
resp.setContentLength((int)file.length());
writeToFile(out, file);
}
private void writeToFile(OutputStream out, File file)
throws FileNotFoundException, IOException
{
final int BUF_SIZE = 8192;
// write the contents of the file to the output stream
FileInputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
for (int count = 0; (count = in.read(buf)) >= 0;) {
out.write(buf, 0, count);
}
}
finally {
in.close();
}
}
如果您不想从servlet流式传输,然后将文件保存到webroot中的目录中,然后创建指向该位置的src。这样Web服务器就可以完成服务文件的工作。如果你感觉特别聪明,你可以通过timestamp/inode/crc32检查现有文件,并且只有在数据库中发生了变化才能提高性能的情况下将其写出。此文件方法也会自动支持ETag和if-modified-since标题,以便浏览器可以正确缓存文件。
你可以张贴的完整代码...我需要它作为参考。 ..我也有同样的问题...但我没有任何代码将如何.. – Lucky 2013-01-15 13:33:05