最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - How to convert buffer object to image in Javascript? - Stack Overflow

programmeradmin1浏览0评论

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')%>"

This is the code i used in ejs.

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')}`}))

This is the code i used in pure js.

This is the object i consoled in js.

This is the error!

Thank you!

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')%>"

This is the code i used in ejs.

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')}`}))

This is the code i used in pure js.

This is the object i consoled in js.

This is the error!

Thank you!

Share Improve this question edited Dec 20, 2019 at 19:24 Aditya V asked Dec 20, 2019 at 19:10 Aditya VAditya V 5782 gold badges8 silver badges18 bronze badges 4
  • What error, you're not showing it. – Marcos Casagrande Commented Dec 20, 2019 at 19:21
  • oh, sorry. Now edited. – Aditya V Commented Dec 20, 2019 at 19:24
  • Where is: image2.data coming from? – Marcos Casagrande Commented Dec 20, 2019 at 19:26
  • Fetching data from MongoDB with nodejs and passed to javascript using ejs. Then trying to append image after filtering. – Aditya V Commented Dec 20, 2019 at 19:28
Add a comment  | 

1 Answer 1

Reset to default 17

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.

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)}`}))


发布评论

评论列表(0)

  1. 暂无评论