使用Javascript,我正在对WCF服务进行AJAX调用,并返回一个字节数组。如何将其转换为图像并将其显示在网页上?
我意识到这是一个旧线程,但我设法通过Web服务上的AJAX调用来实现这一点,并认为我会分享...
<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];
}
}
}
});
我的'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);
魔术是在这行的AJAX调用中:
document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
请享用!
不使用AJAX调用服务,而是使用Javascript构建图像元素并直接将其指向服务...
var img = document.createElement("IMG");
img.src = "http://url/to/service";
img.alt = "ALT TEXT";
document.body.appendChild(img);
只需确保该服务正确设置内容类型即可。
以下是使用数据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;
}
您可能希望从数据创建data-uri并将其放在img元素的src属性中
只需将它作为Base64
发回:
var sig = new Image;
sig.src = 'data:image/png;base64,' + $('#Signature').val();
在我的情况下,我使用Hidden
Input
与Id
的Signature
来存储Base64
数据
晚会,但如果您的回答看起来像
[137,80,78,71,13,10,26,10,0,...]
你可以用这个:
var imgsrc = "data:image/png;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array([137,80,78,71,13,10,26,10,0,...])));
以jQuery为例:
var myImage = $('< img src="data:image/jpg; base64," + bytesarray + "/>"');