Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active June 1, 2020 23:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ugarz/fc6cba3e05d6f1c367fa to your computer and use it in GitHub Desktop.
Save Ugarz/fc6cba3e05d6f1c367fa to your computer and use it in GitHub Desktop.
Encoding and Decoding images in base64 with Nodejs

Encoding and Decoding images in base64 with Node

Take a trump.jpg and launch this gist.

trump.jpg

var fs = require('fs');

function base64_encode(file) {
    console.time('encoding')
    var bitmap = fs.readFileSync(file);
    var result =  new Buffer(bitmap).toString('base64');
    console.timeEnd('encoding')
    return result;
}

function base64_decode(base64str, file) {
    console.time('decoding')
    var bitmap = new Buffer(base64str, 'base64');
    fs.writeFileSync(file, bitmap);
    console.timeEnd('decoding')
}

var base64str = base64_encode('trump.jpeg');
console.log(base64str)
base64_decode(base64str, 'copy.jpg');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment