Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gixxerblade/345e6b7810a1c0a7e5b77662905a52f4 to your computer and use it in GitHub Desktop.
Save gixxerblade/345e6b7810a1c0a7e5b77662905a52f4 to your computer and use it in GitHub Desktop.
Node.js convert an image to Base 64
//http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
// convert image to base64 encoded string
var base64str = base64_encode('salvarDocumento.png');
console.log(base64str);
// convert base64 string back to image
base64_decode(base64str, 'copy_salvarDocumento.png');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment