NodeJS write base64 image-file

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
});

try this simple way

 var imgData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg==';
var base64Data = imgData.replace(/^data:image\/png;base64,/, "");


require("fs").writeFile("out.png", base64Data, 'base64', 
function(err, data) {
if (err) {
    console.log('err', err);
}
console.log('success');

});

focuse at here 1) data:image/png;base there is png 2) replace(/^data:image\/png; here too png and name must save with 3) writeFile("out.png png


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) { ... });

Tags:

Node.Js