[英]Set Image src from image blob
我试图从 API 请求图像并在我的 web 页面中设置img
的 src。 API 返回一个代表 .png 文件的 blob。 此时,我正在使用以下内容请求图像:
const fetchResult = await fetch(imageApiUrl);
const resultBlob = await fetchResult.blob();
console.log(resultBlob);
在控制台中,我可以看到:
Blob {size: [some number], type: "image/png" }
所以,我知道我有结果。 我假设一个斑点。 我现在需要将此 blob 设置为我的 HTML 中的img
源,如下所示:
<img id="profilePicture" alt="Profile Picture" height="250" width="250" />
我有这个:
var profilePicture = document.getElementById('profilePicture');
如何将 profilePicture 元素的 src 设置为 blob?
您可以使用URL.createObjectURL
来创建指向内存中图像的临时 URL:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.