Giallo
Giallo

Reputation: 795

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!

Upvotes: 16

Views: 35527

Answers (3)

Kiochan
Kiochan

Reputation: 487

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');

Upvotes: 18

Giallo
Giallo

Reputation: 795

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.

Upvotes: 6

Jorgen
Jorgen

Reputation: 176

You need to add img to the DOM.

Also if you are generating the buffer in the main process you need to pass it on the the render process of electron.

Upvotes: 2

Related Questions