简体   繁体   中英

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!

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM