Chris Mendez in Javascript, For Developers, NodeJS

NodeJS: Create a Base64 image from a PNG or JPG

There are many good reasons for converting images into Base64 including:

  • Storing an image into a database directly.
  • Returning an image to a browser through an API.
  • Sending an image to an API as part of a POST request.

Here's the snippet I use.

var fs  = require('fs')

function base64_encode(file) {  
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');

var bitmap = base64_encode("./path/to/image.jpg");