Last active
March 16, 2024 21:00
-
-
Save crspiccin/790796a68e7178404de4 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'); |
No need to use two steps when you can use just one:
function base64_encode(file) {
const bitmap = fs.readFileSync(file, { encoding: 'base64' });
}
If you have only one option, you can directly specify it
function base64_encode(file) {
const base64 = fs.readFileSync(file, 'base64');
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why the need to reallocate another buffer?