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.


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);
  image.src = src;
  if (image.complete || image.complete === undefined) {
    image.src = "data:image/gif;base64, R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    image.src = src;
  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.


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 () {
  };'GET', url);
  xhRequest.responseType = 'blob';
toDataURL('', 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>
    <title>Title of the document</title>
    <input type="file" onchange="encodeImageFileAsURL(this)" />
      function encodeImageFileAsURL(element) {
        let file = element.files[0];
        let reader = new FileReader();
        reader.onloadend = function() {
          document.write('RESULT: ', reader.result);

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