Using JavaScript to display a Blob

353,109

Solution 1

The problem was that I had hexadecimal data that needed to be converted to binary before being base64encoded.

in PHP:

base64_encode(pack("H*", $subvalue))

Solution 2

You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();

And the response function looks like this:

function response(e) {
   var urlCreator = window.URL || window.webkitURL;
   var imageUrl = urlCreator.createObjectURL(this.response);
   document.querySelector("#image").src = imageUrl;
}

We just have to make an empty image element in HTML:

<img id="image"/>

Solution 3

If you want to use fetch instead:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Solution 4

You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL.createObjectURL(blob) to convert the Blob into a URL that you pass to img.src.

var data = '424D5E070000000000003E00000028000000EF...';

// Convert the string to bytes
var bytes = new Uint8Array(data.length / 2);

for (var i = 0; i < data.length; i += 2) {
    bytes[i / 2] = parseInt(data.substring(i, i + 2), /* base = */ 16);
}

// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/bmp'});

// Use createObjectURL to make a URL for the blob
var image = new Image();
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);

You can try the complete example at: http://jsfiddle.net/nj82y73d/

Solution 5

In your example, you should createElement('img').

In your link, base64blob != Base64.encode(blob).

This works, as long as your data is valid http://jsfiddle.net/SXFwP/ (I didn't have any BMP images so I had to use PNG).

Share:
353,109
GAgnew
Author by

GAgnew

I am a software developer in Ontario.

Updated on August 16, 2021

Comments

  • GAgnew
    GAgnew over 2 years

    I am retrieving a Blob image from a database, and I'd like to be able to view that image using JavaScript. The following code produces a broken image icon on the page:

    var image = document.createElement('image');
        image.src = 'data:image/bmp;base64,'+Base64.encode(blob);
        document.body.appendChild(image);
    

    Here is a jsFiddle containing all the code required, including the blob. The completed code should properly display an image.

  • GAgnew
    GAgnew over 12 years
    Good point on the img. You should note that 'img' is an html image element where 'image' is a html input element of type image, although in this case it did not make a difference. I am assuming that the image data is valid, as it is coming from a 3rd party source. Do you know anyway of testing this? Or an easy site that gives blob from uploaded image? I would like to test BMP's
  • Agent47DarkSoul
    Agent47DarkSoul over 8 years
    The important line is the urlCreator.createObjectURL(blob) which returns a imageUrl which can be assigned to an image src.
  • Ralpharoo
    Ralpharoo over 5 years
    Don't forget to revoke the created URL once you've finished with it by calling; revokeObjectURL
  • Satish Patro
    Satish Patro about 5 years
    Will this automatically convert base64 as image is base64 encoded?
  • elliotwesoff
    elliotwesoff over 4 years
    The "blob" in your fiddle isn't actually a Blob. You used a base64 encoded string.
  • Christian Ulbrich
    Christian Ulbrich over 4 years
    I'd assume, that OP's image is in some kind of field in a db, i.e. OP can't get it directly. If he'd able to do so, he would most likely use an img - tag directly instead of doing XHR / fetch; because both are prone to SOP.
  • tinyCoder
    tinyCoder almost 4 years
    I love you.. i spent 4 hours trying to solve until I found this.
  • zanderwar
    zanderwar over 3 years
    What happens if (typeof URL !== "function") {}
  • Ogglas
    Ogglas about 3 years
    If you vote down please add a comment why. Hard to improve answers otherwise.
  • José Henrique
    José Henrique almost 2 years
    That worked like a charm. Also, IDK why people are not talking about the fact that axios can return blobs by just adding responseType: 'blob'. That saved me the hassle of converting anything. Also tested on chrome, both window.URL andwindow.webkitURL are truthy