[英]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.我试图从 API 请求图像并在我的 web 页面中设置img
的 src。 The API returns a blob that represents a.png file. API 返回一个代表 .png 文件的 blob。 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:我现在需要将此 blob 设置为我的 HTML 中的img
源,如下所示:
<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?如何将 profilePicture 元素的 src 设置为 blob?
You could use URL.createObjectURL
in order to create a temporary URL that points to the in-memory image:您可以使用URL.createObjectURL
来创建指向内存中图像的临时 URL:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.