How to convert a byte array into an image?
Solution 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:
<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!
Solution 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.
Solution 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)
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;
}
Solution 4:
Late to the party but if your response looks like
[137,80,78,71,13,10,26,10,0,...]
you can use this:
<img id="image" src="" />
var imgsrc = "data:image/png;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array([137,80,78,71,13,10,26,10,0,...])));
document.getElementById('image').src = imgsrc;