如何在Javascript中将缓冲区对象转换为图像? [英] How to convert buffer object to image in Javascript?
问题描述
我只是试图将图像作为缓冲区添加到mongodb,然后尝试转换回图像.在ejs中,效果很好.
I just tried to add image as buffer to mongodb and tried to convert back to image. In ejs, it worked fine.
src ="data:image/png; base64,<%= project.image1.toString('base64')%>"
这是我在ejs中使用的代码.
This is the code i used in ejs.
但是当我尝试通过纯js将其附加到元素上时,它会显示错误
But when i tried to append this to an element through pure js, it shows error
$('#two').prepend($('<img>',{id:'theImg2',src:`data:image/png;base64,${ selected[0].image2.data.toString('base64')}`}))
这是我在纯js中使用的代码.
This is the code i used in pure js.
这是我在js中控制台的对象.
This is the object i consoled in js.
这是错误!
谢谢!
推荐答案
JavaScript中没有Node.js缓冲区中存在的 .toString('base64')
,因此您只是在调用在 Object
上的 .toString
,它确实会输出: [Object Object]
,这就是您所得到的.
There's no .toString('base64')
in JavaScript, that exists in Node.js Buffers, so you're just calling .toString
on an Object
, which will indeed output: [Object Object]
which is what you're getting.
相当于Node.js buffer.toString('base64')
是:
The equivalent of Node.js buffer.toString('base64')
would be:
function toBase64(arr) {
//arr = new Uint8Array(arr) if it's an ArrayBuffer
return btoa(
arr.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
}
$('#two').prepend($('<img>',{id:'theImg2',src:`data:image/png;base64,${toBase64( selected[0].image2.data)}`}))
这篇关于如何在Javascript中将缓冲区对象转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!