[英]Conversion of the binary data string of image file to a Blob
我正在嘗試將從 API 檢索到的數據轉換為Blob
,以便能夠在我的頁面上將其顯示為圖像。
在響應中,我得到了瀏覽器控制台中的數據字符串,如下所示。 我假設它只是一個文件的二進制數據(它看起來像我)。
我使用此代碼將字符串轉換為Blob
:
const convertBinaryToBlob = (binary: string, contentType: string): Blob => {
const uInt8Array = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
uInt8Array[i] = binary.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
};
它生成得很好,以及Blob
object URL,所以我可以把它作為圖像的src
。 問題是圖像無法被瀏覽器顯示,因為它包含一些錯誤。
這里有什么問題? 我怎樣才能讓它工作?
當我使用curl
對其進行測試時,我使用以下命令:
curl -X 'GET' 'http://localhost:8000/images/file/6' -H 'accept: */*' --output img.png
output 文件可以正常工作。 來自curl
的響應標頭:
HTTP/1.1 200 OK
date: Tue, 25 Jan 2022 20:05:30 GMT
server: uvicorn
content-type: image/png
content-length: 3099363
last-modified: Sun, 23 Jan 2022 18:12:08 GMT
etag: 38e1bb48826eab759ab7220bc805124b
Blob 不是有效的圖像源。 您必須將二進制數據轉換為 base64 以便您可以將其作為圖像源傳遞。
將 binaryString 替換為您的二進制數據。
const encodeBase64 = (data) => {
return Buffer.from(data).toString('base64');
}
var base64EncodedStr = encodeBase64(decodeURI(encodeURIComponent(binaryString)));
var src = "data:image/png;base64," + base64EncodedStr ;
將您的圖像源設置為等於 src 變量。
png 也可能是另一種圖像格式。
由這篇文章組成的代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.