15

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!

Giallo
  • 785
  • 2
  • 10
  • 26

3 Answers3

17

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');
droduit
  • 55
  • 1
  • 7
Kiochan
  • 457
  • 1
  • 7
  • 12
  • 1
    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. – sparkitny Jan 22 '18 at 02:20
6

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.

Giallo
  • 785
  • 2
  • 10
  • 26
2

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.

Jorgen
  • 176
  • 1
  • 5