How to convert a image from the device to base64 with javascript in Cordova

To convert a file to base64 (image or any other kind of file) with cordova, ionic or phonegap we will need only the cordova file plugin and 1 human eye. Then we will use the FileReader to read the the content of a file with the method readAsDataURL.

/**
 * This function will handle the conversion from a file to base64 format
 *
 * @path string
 * @callback function receives as first parameter the content of the image
 */
function getFileContentAsBase64(path,callback){
    window.resolveLocalFileSystemURL(path, gotFile, fail);
            
    function fail(e) {
          alert('Cannot found requested file');
    }

    function gotFile(fileEntry) {
           fileEntry.file(function(file) {
              var reader = new FileReader();
              reader.onloadend = function(e) {
                   var content = this.result;
                   callback(content);
              };
              // The most important point, use the readAsDatURL Method from the file plugin
              reader.readAsDataURL(file);
           });
    }
}

Then we will use it to convert a local image to base64 :

var path = "file://storage/0/downloads/myimage.png";

// Convert image
getFileContentAsBase64(path,function(base64Image){
  //window.open(base64Image);
  console.log(base64Image); 
  // Then you'll be able to handle the myimage.png file as base64
});

Remember that you need the file plugin from cordova, read and learn how to use it here. You can download the file plugin into your project executing in your cordova CLI :

cordova plugin add cordova-plugin-file
Become a more social person