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

  • Storing an image into a NoSQL database directly.
  • Serving an image to a client browser through an API.
  • Sending an image to AWS Rekognition through a POST request.

Simple Example

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");

Advanced Example

This example does the same thing but it's wrapped as a JakeJS file so that you can encode the bitmap file and save the base64 text. To make this work follow these steps:

  1. Install JakeJS npm install --save-dev jake
  2. Create a Jakefile.js file.
  3. Paste the code below into Jakefile.js.
  4. Run the command jake base64:encode[./path/to/bitmap/file.png]
var fs  = require('fs'),
path = require('path')

desc('Jakefile default.');
task('default', { async: true }, function(){
  //Look inside of /jakelib
})

namespace('base64', function () {
  
  desc('Create a base64 image');
  task('encode', { async: true }, function(filePath){
    // Create a base64 image
    var bitmap = encode(filePath);
    // Save base64 text.
    var t = jake.Task['base64:save'];
        t.invoke.apply(t, [filePath,bitmap]);

    // Encode the bitmap file.
    function encode(file) {
      // read binary data
      var bitmap = fs.readFileSync(file);
      // convert binary data to base64 encoded string
      return new Buffer(bitmap).toString('base64');
    }    
  });
  
  
  desc('Save a base64 image');
  task('save', { async: true }, function(filePath, base64){
    // Get name of file only
    var fileName = filePath.split("/").slice(-1)[0]
    // Create new filePath
    var textPath = path.join(".", "public", "base64", fileName + ".txt");
    
    function save(textPath){
      // Write to disk
      fs.writeFile(textPath, base64, function(err){
        if(err) return console.log(err);
        console.log("File Created: ", textPath)
      })      
    }
    
  });
});


Related