How to Convert an Image to Base64 String in JavaScript

08/03/2021

Contents

In this article, you will learn how to convert an image to Base64 string in JavaScript.

Converting an image to Base64 string in JavaScript

Converting an image to Base64 string in JavaScript is a common task that can be accomplished with just a few lines of code.

Load the image

The first step is to load the image that you want to convert into a Base64 string. This can be done using the Image object in JavaScript. Here is an example:

const img = new Image();
img.src = 'path/to/image.jpg';

Convert the image to Base64 string

Once the image is loaded, the next step is to convert it into a Base64 string. This can be done using the Canvas API in JavaScript. Here is an example:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

canvas.width = img.width;
canvas.height = img.height;

ctx.drawImage(img, 0, 0);

const dataURL = canvas.toDataURL();

In the above example, we create a canvas element and get its context using the getContext() method. We then set the dimensions of the canvas to match that of the image and draw the image on the canvas using the drawImage() method. Finally, we use the toDataURL() method to convert the image to a Base64 string.

Output the base64 string

The final step is to output the Base64 string. This can be done by assigning it to the src attribute of an img element. Here is an example:

const base64Img = document.createElement('img');
base64Img.src = dataURL;

document.body.appendChild(base64Img);

In the above example, we create an img element and assign the Base64 string to its src attribute. We then append the img element to the body of the HTML document.

Here is the complete code for converting an image to a Base64 string in JavaScript:

const img = new Image();
img.src = 'path/to/image.jpg';

img.onload = function() {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

  canvas.width = img.width;
  canvas.height = img.height;

  ctx.drawImage(img, 0, 0);

  const dataURL = canvas.toDataURL();

  const base64Img = document.createElement('img');
  base64Img.src = dataURL;

  document.body.appendChild(base64Img);
};

In this example, we use the onload event of the img element to ensure that the image is fully loaded before we attempt to convert it to a Base64 string. This is important because if we try to convert the image before it has fully loaded, the resulting Base64 string may be incomplete or incorrect.