如何显示以字节数组形式存储在HTML/JavaScript中的图像? [英] How to display an image stored as byte array in HTML/JavaScript?
问题描述
我正在用HTML/JavaScript编写网页.我正在使用AJAX从后端下载图像.该图像表示为原始字节数组,而不是URL,因此我不能使用标准的<img src="{url}">
方法.
I'm writing a web page in HTML/JavaScript. I'm downloading an image from my backend using AJAX. The image is represented as raw byte array, not an URL, so I can't use the standard <img src="{url}">
approach.
如何向用户显示提及的图像?
How do I display the mentioned image to the user?
推荐答案
尝试将此HTML代码段放入您提供的文档中:
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
然后,在JavaScript端,您可以使用所谓的
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;
或者,使用jQuery:
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
这假定您的图像以PNG格式存储,这非常流行.如果您使用其他图像格式(例如JPEG),请修改 MIME在URL中输入("image/..."
部分).
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.
类似问题:
'data:image/jpg ; base64'和Internet Explorer中的jQuery图像预览
这篇关于如何显示以字节数组形式存储在HTML/JavaScript中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!