-
-
Save siteslave/b20ac8a622f85d2b1754cefdf737c340 to your computer and use it in GitHub Desktop.
Node.js convert an image to Base 64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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