How to convert an image into a Base64 string using JavaScript?

I need to convert images to base64 string. I know I can do this with PHP using base64_encode but is there any built-in function to convert images to base64? How can I solve the problem?

I don’t think there is any built-in function to fulfill your need but you can build your custom base64 encoder.
You have 2 option

  1. Use FileReader and read the image as readAsDataURL
  2. Load the image in html5 canvas and then use toDataURL

Get the image as blob via XMLHttpRequest / AJAX and use the FileReader API readAsDataURL() to convert it to a dataURL:

function base64Encode(url, _callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      _callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

base64Encode('image-url', function(dataUrl) {
  console.log(dataUrl)
});

You can Load the image as Image-Object, then draw the image in canvas and convert the canvas back to a dataURL.

function base64Encode(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    var dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
}

base64Encode('image-url', function(dataUrl) {
  console.log(dataUrl)
});

You can do the same with javascript fetch api.

const base64Encode = function( url ){
    return fetch(url).then(response => response.blob())
    .then(blob => {
        new Promise(function(resolve, reject){
            let reader = new FileReader()
            reader.onloadend = function(){
                resolve(reader.result);
            }
            reader.onerror = reject;
            reader.readAsDataURL(blob);
        });
    });
};
base64Encode('image-url').then(dataUrl => {
    console.log(dataUrl);
});