I've been trying to handle saving images POSTed to nodeJS (and the express framework) to a database, and have been having some trouble. Ignoring all the web processing, I think that I've narrowed down the problem to the way base64 encoding is happening in node. I believe that the oversimplified example below should work, but the output image is always corrupted.
The example (1) loads in an image (2) saves a copy of if (image_orig
) to confirm that node can read the file properly. This always works. (3) I take the image and base64 encode its contents, (4) then decode it. The final output image (image_decoded
) is always corrupted.
Help! (node.js 0.6.0 on OSX Lion)
console.log("starting");
process.chdir(__dirname);
var fs = require("fs");
var image_origial = "image.jpg";
fs.readFile(image_origial, function(err, original_data){
fs.writeFile('image_orig.jpg', original_data, function(err) {});
var base64Image = new Buffer(original_data, 'binary').toString('base64');
var decodedImage = new Buffer(base64Image, 'base64').toString('binary');
fs.writeFile('image_decoded.jpg', decodedImage, function(err) {});
});
I think you are misunderstanding the usage of the encoding argument a bit. If you are going to specify encoding 'binary', then you need to do it consistently. But really you don't need it at all. You seem to be confusing the usage of Buffer vs binary strings.
This next example will work but is very inefficient because changing encodings all the time isn't needed, but I just want to show it to be clear. If you really DID want to have a specific encoding, you need to make sure you are consistent. Every one of those functions has an encoding argument.
This is the right way to do it. Keep everything as a Buffer, except when you make it base64.
Slightly better solution will be to remove all mime types possible:
This is addition to the @Herve's answer.