[英]How do I convert an image from a NodeJS Buffer object to base64 in JavaScript so it can be used in the <img> src attribute?
我正在尝试将我存储在数据库中的图像以缓冲区格式检索到我的前端,并将它们显示为真实图像。 我知道这是可能的,并且我拥有最后解释的正确数据。
后端 NodeJS 和 Express(mongodb 数据库):
router.get("/get-reviews", async (req, res) => {
const review = await Review.find() // Getting all my reviews from my database.
console.log(review[0].img); // Below is my img object where you can see it is in a Buffer format of some sort.
/*
img: {
data: new Binary(Buffer.from("52494646e42300005745425056503820d8230000d018019d012a...", "hex"), 0),
contentType: 'image/webp'
}
*/
res.json({ test_img: review[0].img });
});
前端 Javascript:
async function displayTestImg() {
const data = await fetch("/get-reviews").then(res => res.json())
console.log(data); // Below is what I am retriving from my server, still some buffer format but looks a little different for some reason
/*
contentType: "image/webp"
data:
data: (9196) [82, 73, 70, 70, 228, 35, 0, 0, 87, 69, 66, 80, 86, 80, 56, 32, …]
type: "Buffer"
*/
document.getElementById("my_container_element").innerHTML = `
<img src="data:${ test_img.contentType };base64,${ test_img.data.toString('base64') }">
`;
// Here I am getting the error: GET data:image/webp;base64,[object Object] net::ERR_INVALID_URL
document.getElementById("my_container_element").innerHTML = `
<img src="data:${ test_img.contentType };base64,${ test_img.data.data.toString('base64') }">
`;
// Here I am getting the error: GET data:image/webp;base64,82,73,70,70,228,35,0,0,87,69,66,80,86... net::ERR_INVALID_URL
} displayTestImg();
如您所见,我尝试过的两件事都给了我错误。 这很令人困惑,因为当我通过res.render("index", { test_img: reviews[0].img });
发送数据时并像这样通过 EJS 加载它: <img src="data:<%= review.img.contentType %>;base64,<%= review.img.data.toString('base64') %>" alt="">
,那么它工作得很好,但是? 我需要通过 JavaScript 加载它,那么我该如何实现呢?
好的,最后我找到了答案:
缓冲区 object 仅存在于 NodejS 中,因此当我尝试对其使用.toString('base64') 时,它仅将实际的 object 作为字符串返回,而不是对其进行转换。
我找到的解决方案是这个 function:
function toBase64(arr) {
return window.btoa(arr.reduce((data, byte) => data + String.fromCharCode(byte), ''));
}
所以我所要做的就是输入以下内容并且它有效!
document.getElementById("my_container_element").innerHTML = `
<img src="data:${ test_img.contentType };base64,${ toBase64(test_img.data.data) }">
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.