簡體   English   中英

從圖像 blob 設置圖像 src

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM