如何显示以字节数组形式存储在HTML/JavaScript中的图像? [英] How to display an image stored as byte array in HTML/JavaScript?

查看:582
本文介绍了如何显示以字节数组形式存储在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端,您可以使用所谓的src属性"rel =" noreferrer>数据URL .

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.

类似问题:

将字节显示为图像在.aspx页面上

'data:image/jpg ; base64'和Internet Explorer中的jQuery图像预览

将二进制数据转换为图像控件在ASP.NET中

如何将字节数组转换为图像?

这篇关于如何显示以字节数组形式存储在HTML/JavaScript中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆