Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a JPG image from a Node.js buffer (UInt8Array)

I have a custom Node.JS addon that transfers a jpg capture to my application which is working great - if I write the buffer contents to disk, it's a proper jpg image, as expected.

var wstream = fs.createWriteStream(filename);
wstream.write(getImageResult.imagebuffer);
wstream.end();

I'm struggling to display that image as an img.src rather than saving it to disk, something like

var image = document.createElement('img');
var b64encoded = btoa(String.fromCharCode.apply(null, getImageResult.imagebuffer));
image.src = 'data:image/jpeg;base64,' + b64encoded;

The data in b64encoded after the conversion IS correct, as I tried it on http://codebeautify.org/base64-to-image-converter and the correct image does show up. I must be missing something stupid. Any help would be amazing!

Thanks for the help!

like image 401
Giallo Avatar asked Jul 21 '16 11:07

Giallo


2 Answers

Is that what you want?

// Buffer for the jpg data
var buf = getImageResult.imagebuffer;
// Create an HTML img tag
var imageElem = document.createElement('img');
// Just use the toString() method from your buffer instance
// to get date as base64 type
imageElem.src = 'data:image/jpeg;base64,' + buf.toString('base64');
like image 67
Kiochan Avatar answered Oct 04 '22 20:10

Kiochan


facepalm...There was an extra leading space in the text...

 var getImageResult = addon.getlatestimage();
 var b64encoded = btoa(String.fromCharCode.apply(null, getImageResult.imagebuffer));
 var datajpg = "data:image/jpg;base64," + b64encoded;
 document.getElementById("myimage").src = datajpg;

Works perfectly.

like image 20
Giallo Avatar answered Oct 04 '22 21:10

Giallo