Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created April 16, 2018 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save akirattii/a0c4ac2a1ae5d95c765d44c0f0be4d0e to your computer and use it in GitHub Desktop.
Save akirattii/a0c4ac2a1ae5d95c765d44c0f0be4d0e to your computer and use it in GitHub Desktop.
Example: How to write an image from data URI and read it.
const fs = require('fs');
const dataUri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
const outputFilename = "output";
writeImage(dataUri, outputFilename);
readImage(outputFilename + ".png");
function writeImage(dataUri, outputFilename) {
const regex = /^data:.+\/(.+);base64,(.*)$/;
const matches = dataUri.match(regex);
const ext = matches[1];
const data = matches[2];
const buffer = new Buffer(data, 'base64');
const outputFilepath = outputFilename + '.' + ext;
fs.writeFileSync(outputFilepath, buffer);
console.log(`*** Image wrote
From dataURI: "${dataUri}"
To file => "${outputFilepath}"`);
}
function readImage(file) {
// read binary data
const bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
const base64str = new Buffer(bitmap).toString('base64');
console.log(`*** Image read
From file: "${file}"
To base64 => "${base64str}"`);
}
/* Log output:
$ node example-data-uri-image-write-read.js
*** Image wrote
From dataURI: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
To file => "output.png"
*** Image read
From file: "output.png"
To base64 => "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment