Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Image src from image blob

Tags:

javascript

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?

like image 488
Dev Avatar asked Oct 28 '25 13:10

Dev


1 Answers

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;
like image 86
Guerric P Avatar answered Oct 31 '25 13:10

Guerric P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!