Dev
Dev

Reputation: 299

Set Image src from image blob

I have trying to request an image from an API and set the src of an img in my web page. The API returns a blob that represents a .png file. At this time, I'm requesting the image using the following:

const fetchResult = await fetch(imageApiUrl);
const resultBlob = await fetchResult.blob();
console.log(resultBlob);

In the console, I can see:

Blob {size: [some number], type: "image/png" }

So, I know that I have a result. I assume a blob. I now need to set this blob as the source of an img in my HTML, which looks like this:

<img id="profilePicture" alt="Profile Picture" height="250" width="250" />

I have this:

var profilePicture = document.getElementById('profilePicture');

How do I set the src of the profilePicture element to the blob?

Upvotes: 4

Views: 6039

Answers (1)

Guerric P
Guerric P

Reputation: 31815

You could use URL.createObjectURL in order to create a temporary URL that points to the in-memory image:

let url = URL.createObjectURL(resultBlob);

const img = document.getElementById('profilePicture');
img.src = url;

Upvotes: 3

Related Questions