How to Convert the Image into a Base64 String Using JavaScript

There are several approaches in JavaScript that can help you with converting the image into a Base64 string.

Canvas

Firstly, create a canvas, then load the image into it and use toDataURL() to get the Base64 representation. In fact, it is a data URL, but it contains the Base64-encoded image:

function toDataURL(src, callback, outputFormat) {
  let image = new Image();
  image.crossOrigin = 'Anonymous';
  image.onload = function () {
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    let dataURL;
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  image.src = src;
  if (image.complete || image.complete === undefined) {
    image.src = "data:image/gif;base64, R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    image.src = src;
  }
}
toDataURL('https://www.gravatar.com/avatar/0c6523b4d3f60hj548962bfrg2350',
  function (dataUrl) {
    console.log('RESULT:', dataUrl)
  }
)

This can only be useful if you don’t need the original Base64 string or original image type. Be aware that this method may return different results for the same image depending on the browser and operating system. It will return not only different Base64 values but also different images.

FileReader

Firstly, load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a dataURL:

function toDataURL(url, callback) {
  let xhRequest = new XMLHttpRequest();
  xhRequest.onload = function () {
    let reader = new FileReader();
    reader.onloadend = function () {
      callback(reader.result);
    }
    reader.readAsDataURL(xhRequest.response);
  };
  xhRequest.open('GET', url);
  xhRequest.responseType = 'blob';
  xhRequest.send();
}
toDataURL('https://www.avatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function (dataUrl) {
  console.log('RESULT:', dataUrl)
})

This approach has better compression and works for other file types as well.

Images from the local file system

If you need to convert images from the user’s file system, you should use the FileReader API:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="file" onchange="encodeImageFileAsURL(this)" />
    <script>
      function encodeImageFileAsURL(element) {
        let file = element.files[0];
        let reader = new FileReader();
        reader.onloadend = function() {
          document.write('RESULT: ', reader.result);
        }
        reader.readAsDataURL(file);
      }
    </script>
  </body>
</html>

The FileReader object allows web apps to read the contents of files stored on the user's computer asynchronously, using File or Blob objects to specify the file or data to read.


Do you find this helpful?

Related articles