4

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?

1

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.