How to Use the Fetch API to Get an Image from a URL?

Sometimes, we want to use fetch API to Get an image from a URL.

In this article, we’ll look at how to use fetch API to Get an image from a URL.

Use the Fetch API to Get an Image from a URL

To use fetch API to Get an image from a URL, we can call the blob method on the response object.

Then we can use FileReader to read the blob into a base64 string.

For instance, we write:

const imageUrl = "https://i.picsum.photos/id/566/200/300.jpg?hmac=gDpaVMLNupk7AufUDLFHttohsJ9-C17P7L-QKsVgUQU";

(async () => {
  const response = await fetch(imageUrl)
  const imageBlob = await response.blob()
  const reader = new FileReader();
  reader.readAsDataURL(imageBlob);
  reader.onloadend = () => {
    const base64data = reader.result;
    console.log(base64data);
  }
})()

We call fetch with imageUrl to make a GET request to the imageUrl and return a promise with the response object.

Then we call response.blob to return a promise with the blob data of the image.

Next, we create a FileReader instance and set the onloadend property to a function that gets the base64 string from the blob with the reader.result property.

And then we log the base64data value in the console.

Conclusion

To use fetch API to Get an image from a URL, we can call the blob method on the response object.

Then we can use FileReader to read the blob into a base64 string.