Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS - Encoding images in base64 using Buffer

Tags:

I'm trying to encode an image using base64 in Node.JS to pass along to the PostageApp API as an attachment. I thought I had it working but it attaches a 1K file that isn't exactly what I was looking for.

Here's my code:

 var base64data;   fs.readFile(attachment, function(err, data) {    base64data = new Buffer(data).toString('base64');  }); 

And here's the part of the API call I am making:

 attachments: {    "attachment.txt" : {      content_type: "application/octet-stream",      content: base64data    },  } 

I'm a bit lost, not being so great with Node, but I thought it would work. Any help would be appreciated!

like image 543
JonLim Avatar asked Aug 15 '11 17:08

JonLim


People also ask

How do you decode a binary buffer to an image in node JS?

from(data); //or Buffer. from(data, 'binary') let imgData = new Blob(binary. buffer, { type: 'application/octet-binary' }); let link = URL. createObjectURL(imgData); let img = new Image(); img.

What is Base64 buffer?

The buffer class can be used to encode a string into a series of bytes. The Buffer. from() method takes a string as an input and converts it into Base64. The converted bytes can be changed again into String. The toString() method is used for converting the Base64 buffer back into the string format.

How do I decode buffer data in node JS?

In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.

Can you Base64 encode an image?

Base64 is an encoding algorithm that converts any characters, binary data, and even images or sound files into a readable string, which can be saved or transported over the network without data loss. The characters generated from Base64 encoding consist of Latin letters, digits, plus, and slash.


2 Answers

fs.readFile(attachment, function(err, data) {    var base64data = new Buffer(data).toString('base64');    [your API call here] }); 

It takes some time until the results are there, so by the time you've got the data, the outer scopes execution is already over.

like image 111
thejh Avatar answered Oct 01 '22 01:10

thejh


Just specify "base64" as the encoding. Per the docs:

If no encoding is specified, then the raw buffer is returned.

fs.readFile(attachment, {encoding: 'base64'}, function(err, base64data) {    [your API call here] }); 
like image 25
functionvoid Avatar answered Oct 01 '22 03:10

functionvoid