How to Display an Image Stored as Byte Array in Html/JavaScript

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

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

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

  • Displaying a byte array as an image using JavaScript

  • Display bytes as images on an .aspx page

  • 'data:image/jpg;base64' and jQuery image preview in Internet Explorer

  • Convert from binary data to an image control in ASP.NET

  • How to convert a byte array into an image?

Displaying a byte array as an image using JavaScript

If you have the byte array, you first convert it to Base64String and then you place it on an img tag like that (for a PNG image):

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

Similar Stack Overflow questions:

  • Display bytes as images on an .aspx page

  • 'data:image/jpg;base64' and jQuery image preview in Internet Explorer

  • Convert from binary data to an image control in ASP.NET

How do I display a byte array image from a backend that uses AWS S3, in a React component?

This approach downloads the image, gets the byte array, converts it to a Blob and stuffs the binary data into a magic url you can use for the image source.

const IMAGE_URL = "https://placekitten.com/200/300";

const fetchImage = async (url) => {
try {
const response = await fetch(url);
const imageBytes = await response.arrayBuffer();
var blob = new Blob([imageBytes], { type: "image/jpeg" });
var imageUrl = URL.createObjectURL(blob);
return imageUrl;
} catch (error) {
console.log("ERROR:", error);
}
};

(async () => {
const imageSrc = await fetchImage(IMAGE_URL);
console.log(imageSrc);
document.getElementById("kittenImage").src = imageSrc;
})();

document.getElementById("app").innerHTML = `
<h1>Kitty!</h1>
<image id='kittenImage'>
`;
<!DOCTYPE html>
<html>

<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>

<body>
<div id="app"></div>

<script src="src/index.js">
</script>
</body>

</html>

How to convert a byte array into an image?

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!

Set img src from Byte Array

Replace the jpg with the type of image, and [your byte array] with your byte array. You need to convert it to base64 if it isn't already.

<img id="profileImage" src="data:image/jpg;base64, [your byte array]">

Display image from a string of bytes

Did you ever tried this one?

document.getElementById("img").src = "data:image/png;base64," + input;


Related Topics



Leave a reply



Submit