Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert buffer object to image in Javascript?

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. Image Buffer

This is the object i consoled in js.

Error that i am getting

This is the error!

Thank you!

like image 507
Aditya V Avatar asked Dec 20 '19 19:12

Aditya V


Video Answer


1 Answers

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


like image 160
Marcos Casagrande Avatar answered Sep 20 '22 14:09

Marcos Casagrande