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 OverflowYou 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 convert-base64-to-image
» npm install base64-to-image
» npm install node-base64-image
» npm install node-base64-img
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!');
});
You can use png-to-jpeg module. Assuming the 'data' is in string form :
const fs = require("fs");
const pngToJpeg = require('png-to-jpeg');
const imgStr = 'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t.....';
const buffer = new Buffer(imgStr.split(/,\s*/)[1],'base64');
pngToJpeg({quality: 90})(buffer).then(output => fs.writeFileSync("./some-file.jpeg", output));
Ok, because I'm a professional Googler (just kiding 😂), I found something for you, firstly, you'll have to install ATOB for NodeJS, now, just use it to decode the base64 string, like this :
(function () {
"use strict";
var atob = require('atob');
var b64 = ; //your base64 string
var bin = atob(b64);
var fs = require('fs');
fs.writeFile("./test.jpg", bin, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}());
Actually, I'm not using NodeJS, so I can't tell you more than that, I hope that it will solve your problem!
You have to strip the url meta information from it, the data:image/jpeg part. (Reiterating what @CBroe said) Here is a small function to return the correct information from the input string.
var data = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg==';
function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}
var imageBuffer = decodeBase64Image(data);
console.log(imageBuffer);
// { type: 'image/jpeg',
// data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 b4 00 00 00 2b 08 06 00 00 00 d1 fd a2 a4 00 00 00 04 67 41 4d 41 00 00 af c8 37 05 8a e9 00 00 ...> }
Then you can save the buffer using your above method.
fs.writeFile('test.jpg', imageBuffer.data, function(err) { ... });
Another way is to use fs.writeFile with encoding option base64 after stripping out the meta information.
var image = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg==';
var data = image.replace(/^data:image\/\w+;base64,/, '');
fs.writeFile(fileName, data, {encoding: 'base64'}, function(err){
//Finished
});
BufferList is obsolete, as its functionality is now in Node core. The only tricky part here is setting request not to use any encoding:
var request = require('request').defaults({ encoding: null });
request.get('http://tinypng.org/images/example-shrunk-8cadd4c7.png', function (error, response, body) {
if (!error && response.statusCode == 200) {
data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString('base64');
console.log(data);
}
});
If anyone encounter the same issue while using axios as the http client, the solution is to add the responseType property to the request options with the value of 'arraybuffer':
let image = await axios.get('http://aaa.bbb/image.png', {responseType: 'arraybuffer'});
let returnedB64 = Buffer.from(image.data).toString('base64');
Hope this helps