[javascript] Using JavaScript to display a Blob

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.

This question is related to javascript image base64 blob

The answer is


I guess you had an error in the inline code of your image. Try this :

_x000D_
_x000D_
var image = document.createElement('img');_x000D_
    _x000D_
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";_x000D_
    _x000D_
image.width=100;_x000D_
image.height=100;_x000D_
image.alt="here should be some image";_x000D_
    _x000D_
document.body.appendChild(image);
_x000D_
_x000D_
_x000D_

Helpful link :http://dean.edwards.name/my/base64-ie.html


In the fiddle your blob isn't a blob, it's a string representation of hexadecimal data. Try this on a blob and your done

var image = document.createElement('img');
let reader=new FileReader()
reader.addEventListener('loadend',()=>{
  let contents=reader.result
  image.src = contents
  document.body.appendChild(image);
})
if(blob instanceof Blob) reader.readAsDataURL(blob)

readAsDataURL give you a base64 encoded image ready for you image element () source (src)


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).


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/


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


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"/>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to base64

How to convert an Image to base64 string in java? How to convert file to base64 in JavaScript? How to convert Base64 String to javascript file object like as from file input form? How can I encode a string to Base64 in Swift? ReadFile in Base64 Nodejs Base64: java.lang.IllegalArgumentException: Illegal character Converting file into Base64String and back again Convert base64 string to image How to encode text to base64 in python Convert base64 string to ArrayBuffer

Examples related to blob

Angular: How to download a file from HttpClient? How do we download a blob url video How to convert Blob to File in JavaScript Saving binary data as file using JavaScript from a browser Inserting Image Into BLOB Oracle 10g How to Display blob (.pdf) in an AngularJS app Difference between CLOB and BLOB from DB2 and Oracle Perspective? JavaScript blob filename without link How to convert Blob to String and String to Blob in java How to go from Blob to ArrayBuffer