如何在 HTML/JavaScript 中显示存储为字节数组的图像?

我正在用 HTML/JavaScript 写一个网页。我正在使用 AJAX 从我的后端下载一个图像。图像表示为原始字节数组,而不是 URL,因此我不能使用标准的 <img src="{url}">方法。

如何向用户显示上述图像?

236536 次浏览

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions: