Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS write base64 image-file

Tags:

node.js

My NodeJS-Server receives a picture base64 encoded.

data:image/jpeg;base64,/9j/4QCcRXhpZgAASUkqAAgAAAA ... CiiigD//Z 

The received data should be saved as jpg. Therefore I use a Buffer and the FileSystemWriter:

var imageBuffer = new Buffer(data, 'base64'); //console = <Buffer 75 ab 5a 8a ... fs.writeFile("test.jpg", imageBuffer, function(err) { //... }); 

the fs.writeFile doesn't throw an error. A jpeg-file is saved, but I can't open it. Image-Viewer says:

File is damaged or too big. 

The original file is 6kb large and the new file 7kb.

like image 518
marcel Avatar asked Nov 28 '13 13:11

marcel


People also ask

How to save image from base64 in Nodejs?

rawBody, base64Data = body. replace(/^data:image\/png;base64,/,""), binaryData = new Buffer(base64Data, 'base64'). toString('binary'); require("fs").

How to convert base64 string into image in Node js?

writeFileSync("new-path. jpg", buffer); Things tend to get a bit more complicated when you want to convert a regular (base64) string into an actual image. You need to first convert your string into Buffer before saving it as a real image otherwise, you're going to run into issues.

How do you decode a binary Buffer to an image in node JS?

from(data); //or Buffer. from(data, 'binary') let imgData = new Blob(binary. buffer, { type: 'application/octet-binary' }); let link = URL. createObjectURL(imgData); let img = new Image(); img.


1 Answers

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) { ... }); 
like image 97
Julian Lannigan Avatar answered Sep 21 '22 01:09

Julian Lannigan