首页 > 解决方案 > 从图像 blob 设置图像 src

问题描述

我试图从 API 请求图像并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" }

所以,我知道我有结果。我假设一个斑点。我现在需要在我的 HTML 中将此 blob 设置为 an 的源,img如下所示:

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

我有这个:

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

如何将 profilePicture 元素的 src 设置为 blob?

标签: javascript

解决方案


您可以使用URL.createObjectURL来创建指向内存中图像的临时 URL:

let url = URL.createObjectURL(resultBlob);

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

推荐阅读