Using Javascript, I'm doing 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?
问题:
回答1:
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:
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!
回答2:
Instead of calling the service with AJAX, use Javascript to build an image element and point it to the service directly...
var img = document.createElement("IMG"); img.src = "http://url/to/service"; img.alt = "ALT TEXT"; document.body.appendChild(img);
Just make sure the service sets the content type properly.
回答3:
Here is JavaScript source to decode PNG, JPEG and GIF image bytes, using the Data URI scheme:
Images.decodeArrayBuffer = function(buffer, onLoad) { var mime; var a = new Uint8Array(buffer); var nb = a.length; if (nb
回答4:
You would probably want to create a data-uri from your data and put it in the src attribute of an img element
回答5:
Just send it back as a Base64
then just:
var sig = new Image; sig.src = 'data:image/png;base64,' + $('#Signature').val();
In my case I am using a Hidden
Input
with an Id
of Signature
to store that Base64
data
回答6:
Using jQuery as an example:
var myImage = $('"');