user4593233
user4593233

Reputation:

How do you save an image (passed in as a base64 encoded string) with Node.js

I created a HTML5 canvas with Phantom.js on my Meteor Application and i am trying to save the Canvas image on disk.

Problem: The saved image file appears to be corrupt (can't open it in an image viewer).

I got a base64 encoded PNG image from the HTML5 Canvas.toDataUrl method. This is what my saved output from the Canvas.toDataUrl() function looks like: WzMyLDMyLDU4LDQ3LDEwOSwxMTEsMTAwLDExNywxMDgsMTAxLDExNSw0NywxMTksMTAxLDk4LDExMiw5NywxMDMsMTAxLDQ2LDEwNiwxMTUsNTgsNTAsNTYsNDksMTBd

This is my Save Routine:

var buffer = new Buffer(JSON.stringify(CanvasString)).toString('base64');
var fs = Meteor.npmRequire("fs");
var fullFileName = fileName + '.png';
fs.writeFileSync(fullFileName, buffer, "binary");

I can view the saved image as plaintext with a text editor like the output above.

Upvotes: 2

Views: 2205

Answers (1)

saimeunt
saimeunt

Reputation: 22696

Try these steps :

// our data URL string from canvas.toDataUrl();
var imageDataUrl = "data:image/png;base64,[...]";
// declare a regexp to match the non base64 first characters
var dataUrlRegExp = /^data:image\/\w+;base64,/;
// remove the "header" of the data URL via the regexp
var base64Data = imageDataUrl.replace(dataUrlRegExp, "");
// declare a binary buffer to hold decoded base64 data
var imageBuffer = new Buffer(base64Data, "base64");
// write the buffer to the local file system synchronously
fsWriteFileSync("/tmp/test.png", imageBuffer);
  • Note : you probably don't want to use fs.writeFileSync to write on disk in Node.JS because it will block the entire Node event loop.

Instead wrap the call using Meteor.wrapAsync :

var fsWriteFileSync = Meteor.wrapAsync(fs.writeFile, fs);

Upvotes: 2

Related Questions