fetch image as blob

How to fetch image as blob in JavaScript?

If you want to fetch an image as a blob using JavaScript, there are several ways to do so. I will explain two methods that I have used before.

Method 1: Using XMLHttpRequest and Blob()

This method involves creating a new XMLHttpRequest object and sending a request to the server to fetch the image. Once the image is received, it is converted to a blob object using the Blob() constructor. Here's how the code looks like:


const xhr = new XMLHttpRequest();
xhr.open('GET', 'path/to/image.jpg', true);
xhr.responseType = 'blob';

xhr.onload = () => {
  if (xhr.status === 200) {
    const blob = new Blob([xhr.response], { type: 'image/jpeg' });
    const imageUrl = URL.createObjectURL(blob);
    
    // Display image in HTML div
    const img = document.createElement('img');
    img.src = imageUrl;
    document.getElementById('myDiv').appendChild(img);
  }
};

xhr.send();

In this code, we create a new XMLHttpRequest object and set its responseType to 'blob'. We then send a GET request to fetch the image. Once it is received, we create a new Blob object using the response data and set its MIME type to 'image/jpeg'. Finally, we create a URL object from the blob and use it as the source for an <img> element that we append to an HTML div with the ID 'myDiv'.

Method 2: Using fetch() and Response.blob()

This method is similar to the previous one, but it uses the fetch() function and the Response.blob() method instead. Here's how the code looks like:


fetch('path/to/image.jpg')
  .then(response => response.blob())
  .then(blob => {
    const imageUrl = URL.createObjectURL(blob);
    
    // Display image in HTML div
    const img = document.createElement('img');
    img.src = imageUrl;
    document.getElementById('myDiv').appendChild(img);
  });

In this code, we use the fetch() function to send a GET request to fetch the image. We then use the Response.blob() method to convert the response to a blob object. Once we have the blob, we create a URL object from it and use it as the source for an <img> element that we append to an HTML div with the ID 'myDiv'.

Both methods are straightforward and easy to implement. You can choose the one that suits your needs best. Keep in mind that you should always handle errors and clean up resources after you're done using them.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe