You can decode the base64 image using following method .
EDITED
To strip off the header
let base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA'; // Not a real image
// Remove header
let base64Image = base64String.split(';base64,').pop();
To write to a file
import fs from 'fs';
fs.writeFile('image.png', base64Image, {encoding: 'base64'}, function(err) {
console.log('File created');
});
Note :- Don’t forget the {encoding: 'base64'} here and you will be good to go.
Answer from Pushprajsinh Chudasama on Stack Overflow
» npm install base64-to-image
» npm install base64-img
» npm install convert-base64-to-image
» npm install b64-to-image
You can decode the base64 image using following method .
EDITED
To strip off the header
let base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA'; // Not a real image
// Remove header
let base64Image = base64String.split(';base64,').pop();
To write to a file
import fs from 'fs';
fs.writeFile('image.png', base64Image, {encoding: 'base64'}, function(err) {
console.log('File created');
});
Note :- Don’t forget the {encoding: 'base64'} here and you will be good to go.
Change encode function like below. Also, keep in mind new Buffer() has been deprecated so use Buffer.from() method.
function encode_base64(filename) {
fs.readFile(path.join(__dirname, filename), function (error, data) {
if (error) {
throw error;
} else {
//console.log(data);
var dataBase64 = Buffer.from(data).toString('base64');
console.log(dataBase64);
client.write(dataBase64);
}
});
}
And decode as Below :
function base64_decode(base64Image, file) {
fs.writeFileSync(file,base64Image);
console.log('******** File created from base64 encoded string ********');
}
client.on('data', (data) => {
base64_decode(data,'copy.jpg')
});
» npm install node-base64-image
» npm install image-to-base64
» npm install node-base64-img
» npm install base64image
One possible problem:
"Error: Invalid base64 string"
To debug, try replacing 1st line with:
var base64Str = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
Another:
An incorrect path as a logical error, runs code without error but not saving the image file as it should. Ie, if the path points to a non-existant directory, misspelled directory or a inaccessable directory.
To debug, try replacing 2nd line with
var path ='./';so it will save in the script directory. Note that '/' leads to no file saved, and an empty string leads to error "Missing mandatory arguments..."
// target is path where you want to save file example /upload/filename.png
fs.writeFile(target, new Buffer(base64Str, "base64"), function (err) {
if(err) console.log(err);
console.log('The file has been saved!');
});