[英]Bug when converting image buffer back to base64
我遇到了一個奇怪的錯誤,當我將 base64 字符串轉換為圖像緩沖區( Buffer.from(image, "base64")
)並返回到 base64 ( .toString("base64")
)時,生成的 base64 字符串丟失了它格式( dataimage/pngbase64
而不是data:image/png;base64
)以及最后缺少g==
。 這會導致圖像“損壞”並且當我將它放在前端的<img />
中時不會呈現。 我正在使用的當前解決方法如下:
image.toString("base64").replace("dataimage/pngbase64", "data:image/png;base64,") + "g=="
但這遠非最佳解決方案,我不想使用這種解決方法。
這是我緩沖圖像( image
是 base64)並將其存儲在數據庫中的地方
t.field("createModel", {
type: $name,
args: { input: nonNull(arg({ type: createModelInput.name })) },
resolve: async (_, args) => {
const { image, name, manufacturerId, identifiers } = args.input;
console.log(image) // correct base64 image from frontend
const buffedImage = Buffer.from(image, "base64");
console.log(buffedImage.toString("base64")) // not the same as image above: missing formatting & g== at the end
return await prisma.model.create({
data: {
image: buffedImage,
name,
identifiers,
manufacturer: {
connect: {
id: manufacturerId,
},
},
},
});
},
});
請告訴我需要任何進一步的信息。
字符串的Base64編碼部分沒有啟動,直到后,
; 的data:
部分是一個方案中, image/png
部分是一個內容類型和base64,
部分是一個指標,接下來它是Base64編碼文本。 因此,當您嘗試將整個字符串用作 Base64 時,您要求轉換非 Base64 數據。
您必須先刪除該前綴,因為它不是 Base64 數據的一部分。 它只是data:
的一部分data:
URI。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.