Javascript 如何将字节数组转换为图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4564119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a byte array into an image?
提问by KevinDeus
Using Javascript, I'm making an AJAX call to a WCF service, and it is returning a byte array. How can I convert that to an image and display it on the web page?
使用 Javascript,我对 WCF 服务进行 AJAX 调用,它返回一个字节数组。如何将其转换为图像并将其显示在网页上?
采纳答案by Nicolai Dutka
I realize this is an old thread, but I managed to do this through an AJAX call on a web service and thought I'd share...
我意识到这是一个旧线程,但我设法通过 Web 服务上的 AJAX 调用来做到这一点,并认为我会分享......
I have an image in my page already:
<img id="ItemPreview" src="" />
AJAX:
$.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', timeout: 10000, url: 'Common.asmx/GetItemPreview', data: '{"id":"' + document.getElementById("AwardDropDown").value + '"}', success: function (data) { if (data.d != null) { var results = jQuery.parseJSON(data.d); for (var key in results) { //the results is a base64 string. convert it to an image and assign as 'src' document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key]; } } } });
我的页面中已经有一张图片:
<img id="ItemPreview" src="" />
阿贾克斯:
$.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', timeout: 10000, url: 'Common.asmx/GetItemPreview', data: '{"id":"' + document.getElementById("AwardDropDown").value + '"}', success: function (data) { if (data.d != null) { var results = jQuery.parseJSON(data.d); for (var key in results) { //the results is a base64 string. convert it to an image and assign as 'src' document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key]; } } } });
My 'GetItemPreview' code queries a SQL server where I have an image stored as a base64 string and returns that field as the 'results':
我的“GetItemPreview”代码查询 SQL 服务器,其中我将图像存储为 base64 字符串,并将该字段作为“结果”返回:
string itemPreview = DB.ExecuteScalar(String.Format("SELECT [avatarImage] FROM [avatar_item_template] WHERE [id] = {0}", DB.Sanitize(id)));
results.Add("Success", itemPreview);
return json.Serialize(results);
The magic is in the AJAX call at this line:
神奇之处在于这一行的 AJAX 调用:
document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
Enjoy!
享受!
回答by Josh Stodola
Instead of calling the service with AJAX, use Javascript to build an image element and point it to the service directly...
不是用 AJAX 调用服务,而是使用 Javascript 构建图像元素并将其直接指向服务......
var img = document.createElement("IMG");
img.src = "http://url/to/service";
img.alt = "ALT TEXT";
document.body.appendChild(img);
Just make sure the service sets the content type properly.
只要确保服务正确设置了内容类型。
回答by Adam Gawne-Cain
Here is JavaScript source to decode PNG, JPEG and GIF image bytes, using the Data URI scheme:
这是使用数据 URI 方案解码 PNG、JPEG 和 GIF 图像字节的 JavaScript 源代码:
Images.decodeArrayBuffer = function(buffer, onLoad) {
var mime;
var a = new Uint8Array(buffer);
var nb = a.length;
if (nb < 4)
return null;
var b0 = a[0];
var b1 = a[1];
var b2 = a[2];
var b3 = a[3];
if (b0 == 0x89 && b1 == 0x50 && b2 == 0x4E && b3 == 0x47)
mime = 'image/png';
else if (b0 == 0xff && b1 == 0xd8)
mime = 'image/jpeg';
else if (b0 == 0x47 && b1 == 0x49 && b2 == 0x46)
mime = 'image/gif';
else
return null;
var binary = "";
for (var i = 0; i < nb; i++)
binary += String.fromCharCode(a[i]);
var base64 = window.btoa(binary);
var image = new Image();
image.onload = onLoad;
image.src = 'data:' + mime + ';base64,' + base64;
return image;
}
回答by Joel'-'
Late to the party but if your response looks like
聚会迟到但如果你的回应看起来像
[137,80,78,71,13,10,26,10,0,...]
you can use this:
你可以使用这个:
<img id="image" src="" />
var imgsrc = "data:image/png;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array([137,80,78,71,13,10,26,10,0,...])));
document.getElementById('image').src = imgsrc;
回答by oligofren
Converting the byte array to base64 when you have the binary byte array is ridiculously expensive, and more importantly; it's totally unnecessary work, as you don't have to do convert it at all in modern browsers! The static URL.createObjectURL
method creates a DOMString
, a short browser-specific url, from the byte array, and you can use the resulting short string in img.src
or similar.
当您拥有二进制字节数组时,将字节数组转换为 base64 是非常昂贵的,而且更重要的是;这是完全不必要的工作,因为您根本不必在现代浏览器中进行转换!静态URL.createObjectURL
方法DOMString
从字节数组中创建一个特定于浏览器的短网址,您可以使用生成的短字符串 inimg.src
或类似内容。
This is infinitely fasterthan solutions that require chaining TextEncoder
and btoa
when all you need is to display an image received in a byte array form.
这比需要链接的解决方案快得多,TextEncoder
而且btoa
您只需要显示以字节数组形式接收的图像。
var blob = new Blob( [ uint8ArrayBuffer ], { type: "image/jpeg" } );
var imageUrl = URL.createObjectURL( blob );
This is using HTML5 APIs, and so will not work on Node or other JS based servers, of course.
这是使用 HTML5 API,因此当然不适用于 Node 或其他基于 JS 的服务器。
// Simulate a call to Dropbox or other service that can
// return an image as an ArrayBuffer.
var xhr = new XMLHttpRequest();
// Use PlaceKitten as a sample image to avoid complicating
// this example with cross-domain issues.
xhr.open( "GET", "https://placekitten.com/200/140", true );
// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
// Obtain a blob: URL for the image data.
var arrayBufferView = new Uint8Array( this.response );
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
var img = document.querySelector( "#photo" );
img.src = imageUrl;
};
xhr.send();
<h1>Demo of displaying an ArrayBuffer</h1>
<p><a href="http://jsfiddle.net/Jan_Miksovsky/yy7Zs/">Originally made by Jan Miksovsky</p>
<img id="photo"/>
回答by kioopi
You would probably want to create a data-uri from your data and put it in the src attribute of an img element
您可能希望从您的数据创建一个 data-uri 并将其放入 img 元素的 src 属性中
回答by Serj Sagan
Just send it back as a Base64
then just:
只需将其发送回Base64
然后即可:
var sig = new Image;
sig.src = 'data:image/png;base64,' + $('#Signature').val();
In my case I am using a Hidden
Input
with an Id
of Signature
to store that Base64
data
在我的情况下,我使用Hidden
Input
带有一个Id
ofSignature
来存储该Base64
数据
回答by molham556
Using jQuery as an example:
以 jQuery 为例:
var myImage = $('< img src="data:image/jpg; base64," + bytesarray + "/>"');