Base-64 encoding images in Node.js

The following example shows how you can base-64 encode an image so you can use it as a data URI.

First, create a new file, app.js, and add the following code:

#!/usr/bin/env node

var fs = require("fs"),
    util = require("util");

var mime = require("mime");

var dataUri = base64Image("./icon4.png");
console.log(dataUri);

function base64Image(src) {
    var data = fs.readFileSync(src).toString("base64");
    return util.format("data:%s;base64,%s", mime.lookup(src), data);
}

Next you need to install the mime module in the same directory as the app.js file created above by typing the following command in your Terminal: npm install mime

Finally, run the app.js file by typing the following command: node app.js and the following output should be displayed in the console:

$ ./app.js 
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB50RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNS4xqx9I6wAAAVBJREFUOI2tlLFKA0EQhr+9i2J1kBDFYG91gYRA0ngpJELQ2KSwlFjYKIidlZVvIFgEXyBYaBH0ESysLATBPiRYWFgEye7eWkSimL1wyg1MM//Mx87O7ghjjCEhc5ICJQ5LRQm9/oDLqzsenl4QgAHK/ir7O5us5JatNcJ2Z73+gKOzCz6kQjguQoAxYELNwlyK89NDK9DaZrvTZTiS4LggBAYBQoDjMhxJ2p1u/DbvH59xU/MYrac0Y8Z6bJgJDaEF9FOPDdNKMev1hVrFh2XTHq9v75GwpYxnjVsH0GrW0UqhtZ52pWg16/FhjVpANu2Ngb88m/Zo1IL4MICg5FthQcmPKomGVSsFpJQopSYupaRaKUTCIr9TuZhnq76O47iTWBhqysX832EA1ze3COf78LnFDBzvRebP3BrbG2tfUx23eXKwOyvd/tH/a4nus083fKdxIODDXwAAAABJRU5ErkJggg==

You can now use the data URI by copy/pasting that string within your CSS or in an <img src="..."> attribute, as seen in the following snippet:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB50RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNS4xqx9I6wAAAVBJREFUOI2tlLFKA0EQhr+9i2J1kBDFYG91gYRA0ngpJELQ2KSwlFjYKIidlZVvIFgEXyBYaBH0ESysLATBPiRYWFgEye7eWkSimL1wyg1MM//Mx87O7ghjjCEhc5ICJQ5LRQm9/oDLqzsenl4QgAHK/ir7O5us5JatNcJ2Z73+gKOzCz6kQjguQoAxYELNwlyK89NDK9DaZrvTZTiS4LggBAYBQoDjMhxJ2p1u/DbvH59xU/MYrac0Y8Z6bJgJDaEF9FOPDdNKMev1hVrFh2XTHq9v75GwpYxnjVsH0GrW0UqhtZ52pWg16/FhjVpANu2Ngb88m/Zo1IL4MICg5FthQcmPKomGVSsFpJQopSYupaRaKUTCIr9TuZhnq76O47iTWBhqysX832EA1ze3COf78LnFDBzvRebP3BrbG2tfUx23eXKwOyvd/tH/a4nus083fKdxIODDXwAAAABJRU5ErkJggg==" />

And the previous snippet outputs the following image:

Leave a Reply

Your email address will not be published.