javascript - 从图像 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?
解决方案
您可以使用URL.createObjectURL
来创建指向内存中图像的临时 URL:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;
推荐阅读
- datadog - 在 Datadog 的仪表板中显示服务的版本
- ruby - 是否有任何真实世界的字体在 CFF 表的顶部字典中指定编码?
- regex - semver 正则表达式比这个更便携或额外覆盖?
- android - Firebase 在父级观察/查询并忽略其中一个子级
- dart - 如何在 Flutter 中移除 AppBar 前导图标周围的额外填充
- python-2.7 - 面对 StaleElementReferenceException:消息:元素不再是有效的问题。请检查是否有出路
- python-3.x - 使用 selenium 在 python3 中执行 javascript 代码时出错
- java - 您可以从 jsp 文件中 <% %> 块中的 servlet 获取会话属性吗?
- windows - 如何在保留其所有配置文件的同时在同级目录中运行可执行文件?
- r - 减少 R 代码的运行时间