Skip to content

Instantly share code, notes, and snippets.

@blenderous
Last active October 19, 2022 08:09
Show Gist options
  • Save blenderous/1114735fa2c86eeed785 to your computer and use it in GitHub Desktop.
Save blenderous/1114735fa2c86eeed785 to your computer and use it in GitHub Desktop.
Convert PNG image to data URI using Node.js
var fs = require('fs');
//
// reference for accessing file system using node.js
// http://www.sitepoint.com/accessing-the-file-system-in-node-js/
fs.readFile('image.png', 'binary', function(error, data) {
var buf = new Buffer(data, 'binary');
var string = buf.toString('base64');
var limit = parseInt(string.length/50);
console.log('Data url of the image.png in not more than 50 characters per line:');
console.log('');
// first line of output
console.log('"data:image/png;base64," +');
for (var i = 1; i <= limit; i++) {
// more output
console.log('"' + string.substring( (i - 1) * 50, i * 50 ) + '" +');
}
// if there's more base64 to the output
if (string.length > limit * 50) {
// final lines of output
console.log('"' + string.substring( limit * 50, string.length ) + '"');
}
console.log('');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment