Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

javascript - How to convert a byte array into an image?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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({
            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':

     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:

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

Enjoy!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...