如何将字节数组转换为图像? [英] How to convert a byte array into an image?

查看:159
本文介绍了如何将字节数组转换为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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...


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

  • I have an image in my page already:

 <img id="ItemPreview" src="" />


  • AJAX:

  • 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字符串,并将该字段作为结果返回:

    My 'GetItemPreview' code queries a SQL server where I have an image stored as a base64 string and returns that field as the 'results':

         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调用具有魔力:

    The magic is in the AJAX call at this line:

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

    享受!

    这篇关于如何将字节数组转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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