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

26,669

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
26,669
Giallo
Author by

Giallo

Updated on July 30, 2022

Comments

  • Giallo
    Giallo almost 2 years

    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!

  • sparkplug
    sparkplug over 6 years
    If you check what has already been posted, the question asker answered his own question. How is your answer different, you have not outlined how it answers the question or how it is different to the other answer.