[英]Convert byte[] to Base64 string for data URI
我知道這可能已被問過10000次,但是,我似乎無法找到問題的直接答案。
我有一個存儲在我的數據庫中的LOB代表一個圖像; 我從數據庫中獲取該圖像,我想通過HTML IMG標記在網頁上顯示它。 這不是我的首選解決方案,但它是一個臨時實施,直到我找到更好的解決方案。
我正在嘗試使用Apache Commons Codec以下列方式將byte []轉換為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
。
這是正確的語法。 可能是您的Web瀏覽器不支持數據URI方案。 請參閱哪些瀏覽器支持數據URI以及哪個版本支持?
此外,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檢查現有文件,只有在DB中發生更改才能將其寫出來,這樣可以提高性能。 此文件方法還將自動支持ETag和if-modified-since標頭,以便瀏覽器可以正確緩存文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.