(Javascript)将字节[]转换为图像

Kev*_*eus 18 javascript ajax wcf image

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

Nic*_*tka 17

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

  • 我的页面中已有一张图片:

     <img id="ItemPreview" src="" />
    
    Run Code Online (Sandbox Code Playgroud)
  • 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];
                    }
                }
            }
        });
    
    Run Code Online (Sandbox Code Playgroud)

我的'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);
Run Code Online (Sandbox Code Playgroud)

魔术是在这行的AJAX调用中:

     document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
Run Code Online (Sandbox Code Playgroud)

请享用!


Joe*_*'-' 6

聚会迟到了,但如果你的回答看起来像

[137,80,78,71,13,10,26,10,0,...]
Run Code Online (Sandbox Code Playgroud)

你可以使用这个:

[137,80,78,71,13,10,26,10,0,...]
Run Code Online (Sandbox Code Playgroud)
<img id="image" src="" />
Run Code Online (Sandbox Code Playgroud)


oli*_*ren 6

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

当您只需要显示以字节数组形式接收的图像时,这比需要链接的解决方案要快得多。TextEncoderbtoa

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

这是使用 HTML5 API,因此当然不适用于 Node 或其他基于 JS 的服务器。

var blob = new Blob( [ uint8ArrayBuffer ], { type: "image/jpeg" } );
var imageUrl = URL.createObjectURL( blob );
Run Code Online (Sandbox Code Playgroud)
// 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();
Run Code Online (Sandbox Code Playgroud)


Jos*_*ola 5

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

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

只要确保服务正确设置了内容类型即可。


Ada*_*ain 5

这是使用数据 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;
}
Run Code Online (Sandbox Code Playgroud)