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

时间:2010-12-30 16:03:05

标签: javascript ajax image wcf

使用Javascript,我正在对WCF服务进行AJAX调用,并返回一个字节数组。如何将其转换为图像并在网页上显示?

8 个答案:

答案 0 :(得分:18)

我意识到这是一个旧线程,但我设法通过Web服务上的AJAX调用来实现这一点,并且认为我会分享...

  • 我的页面中已有图片:

     <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];
                    }
                }
            }
        });
    

我的'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];

享受!

答案 1 :(得分:4)

使用Javascript构建图像元素并直接将其指向服务,而不是使用AJAX调用服务...

var img = document.createElement("IMG");
img.src = "http://url/to/service";
img.alt = "ALT TEXT";
document.body.appendChild(img);

确保服务正确设置内容类型。

答案 2 :(得分:4)

以下是使用数据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;
}

答案 3 :(得分:1)

您可能希望从数据中创建数据uri并将其放在img元素的src属性中

http://en.wikipedia.org/wiki/Data_URI_scheme

答案 4 :(得分:1)

只需将其作为Base64发送回来,然后只需:

var sig = new Image;
sig.src = 'data:image/png;base64,' + $('#Signature').val();

在我的情况下,我使用Hidden Input Id Signature来存储Base64数据

答案 5 :(得分:0)

迟到聚会了,但是如果您的回复像

[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,...])));

答案 6 :(得分:0)

当拥有二进制字节数组时,将字节数组转换为base64非常昂贵,而且更重要的是;这完全是不必要的工作,因为您根本不需要在现代浏览器中进行转换!静态URL.createObjectURL方法从字节数组中创建一个DOMString(一个简短的浏览器特定的url),您可以在img.src或类似名称中使用生成的短字符串。

这比需要链接TextEncoderbtoa的解决方案无限快,当您所需的全部是显示以字节数组形式接收的图像时。

var blob = new Blob( [ uint8ArrayBuffer ], { type: "image/jpeg" } );
var imageUrl = URL.createObjectURL( blob );

这是使用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"/>

答案 7 :(得分:-1)

以jQuery为例:

var myImage = $('< img src="data:image/jpg; base64," + bytesarray + "/>"');