Build awareness and adoption for your software startup with Circuit.

A Comprehensive Guide to Converting Images to Base64 with JavaScript

Explaining how to convert Image to Base64 and discussing use cases, techniques, and some functional examples in simple terms.

A Comprehensive Guide to Converting Images to Base64 with JavaScript | Tushar Kanjariya

Hello Developers 👋, Converting images to Base64 is a technique that allows you to embed images in your HTML or CSS files without having to store the image as a separate file.

It’s a convenient way to reduce the number of HTTP requests your website needs to make, which can improve page load times. In this tutorial, we’ll cover how to convert an image to Base64 using JavaScript.

👉 What is Base64?

Before we dive into the code, let’s first understand what Base64 is.

Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. The ASCII string consists of 64 characters that can be used to represent any 8-bit byte value.

This makes it possible to represent binary data, such as images, as text. Base64 encoding is widely used in web applications to transmit binary data in a safe and efficient manner.

👉 Converting an Image to Base64

To convert an image to Base64 using JavaScript, we need to first load the image into a canvas element, and then use the canvas element to encode the image as Base64.

For Example:

// Get the image element
const img = document.getElementById(''my-image'');

// Create a canvas element
const canvas = document.createElement(''canvas'');

// Set the canvas dimensions to the image dimensions
canvas.width = img.width;
canvas.height = img.height;

// Get the canvas context
const ctx = canvas.getContext(''2d'');

// Draw the image on the canvas
ctx.drawImage(img, 0, 0);

// Get the Base64-encoded data
const dataURL = canvas.toDataURL();

Let’s understand above code step-by-step.

  1. We start by getting the image element using document.getElementById(). You''ll need to replace ''my-image'' with the ID of your own image element.
  2. Next, we create a canvas element using document.createElement(''canvas'').
  3. We set the canvas dimensions to match the image dimensions using the width and height properties.
  4. We get the canvas context using canvas.getContext(''2d'').
  5. We draw the image on the canvas using ctx.drawImage(img, 0, 0). This copies the image data onto the canvas.
  6. Finally, we use canvas.toDataURL() to get the Base64-encoded data.

The dataURL variable contains string for base64 image.

👉 Using the Base64-encoded Image

Converting an image to Base64 using JavaScript can be useful in many different scenarios.

Here are some examples:

  • Embedding images in HTML emails: When you send an email with an image, the image needs to be hosted on a server and referenced by its URL. However, some email clients block external images by default. By converting the image to Base64 and embedding it in the email as a data URL, you can ensure that the image will be displayed even if external images are blocked.
  • Storing images in local storage: If you’re building a web app that needs to store images locally (for example, as part of a user’s profile), you can convert the image to Base64 and store it as a string in local storage. This allows you to store the image data without having to make an HTTP request to a server.
  • Preloading images: If you want to preload images on a page before they’re displayed, you can use JavaScript to convert them to Base64 and preload them as data URLs. This can improve your app’s perceived performance by reducing the time it takes for images to load when they’re actually displayed.

👉 Techniques for Image to Base64 image conversion

There are several techniques to convert an image to Base64 using JavaScript.

1. Using the fetch API and Blob API

fetch(''image.jpg'')
  .then(response => response.blob())
  .then(blob => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = () => {
      const base64data = reader.result;
      console.log(base64data);
    };
  });

2. Using the HTMLImageElement API and canvas element:

const img = new Image();
img.crossOrigin = ''anonymous'';
img.src = ''image.jpg'';
img.onload = () => {
  const canvas = document.createElement(''canvas'');
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext(''2d'');
  ctx.drawImage(img, 0, 0);
  const base64data = canvas.toDataURL(''image/jpeg'');
  console.log(base64data);
};

3. Using the FileReader API and canvas element:

const input = document.querySelector(''input[type="file"]'');
input.addEventListener(''change'', () => {
  const file = input.files[0];
  const reader = new FileReader();
  reader.onload = () => {
    const img = new Image();
    img.src = reader.result;
    img.onload = () => {
      const canvas = document.createElement(''canvas'');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext(''2d'');
      ctx.drawImage(img, 0, 0);
      const base64data = canvas.toDataURL(''image/jpeg'');
      console.log(base64data);
    };
  };
  reader.readAsDataURL(file);
});

All three methods use the same basic steps: load the image file, create a canvas element, draw the image on the canvas, and get the Base64 encoded data URL of the canvas.

The differences lie in how the image file is loaded and how the canvas is created.

👉 Functional Way to Implement Image to Base64 Conversion

There are 3 different functional ways to implement image to base64 conversion that need in real life.

  1. convert an image to base64 from the image URL. (Most Useful)
  2. Uploading a local image to convert to base64.
  3. Convert pasted image from the clipboard to base64. (Most Useful)

💻 Convert Image to base64 from Image URL

To convert an image to base64 from an image URL in JavaScript, you can use the fetch API to get the image data, and then use the FileReader API to read the image data as a base64 string.

Here''s an example function that does this:

function imageToBase64(url, callback) {
  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = () => {
        const base64String = reader.result;
        callback(base64String);
      };
    });
}

You can use this function like this:

imageToBase64(imageUrl, function (base64String) {
  document.body.style.background = `url(${base64String}) no-repeat center`;
  console.log(base64String);
});

This will log the base64 string of the image to the console and set base64 image to document the background.

You can use this base64 string to display the image or to send it to a server as part of a form or API request.

Codepen: Convert Image to base64 from Image URL

💻 Uploading a local image to convert to base64

You can use the FileReader API to read a local file and then use the btoa function to convert the binary data to a base64 string.

For example:

const fileInput = document.getElementById("file-input");
const convertButton = document.getElementById("convert-button");
const outputDiv = document.getElementById("output");
var base64String = "";
fileInput.addEventListener("change", () => {
  const file = fileInput.files[0];
  const reader = new FileReader();

  reader.onload = () => {
    base64String = btoa(reader.result);
  };

  reader.readAsBinaryString(file);
});

convertButton.addEventListener("click", () => {
  let imgElement = document.getElementById("imageBase64");
  imgElement.src = `data:image/png;base64,${base64String}`; // set image src
  console.log(base64String);
});

Codepen: Uploading a local image to convert to base64

💻 Convert pasted image from clipboard to base64

Paste images from a clipboard is useful at work, for example, we can share text with original style by cutting it as an image.

The data read from the clipboard is blob type, so we can continue the file FileReader to convert the data to base64. The following code shows how to do it:

const imageContainer = document.getElementById(''image-container'');

document.addEventListener(''paste'', function (e) {
  const items = e.clipboardData.items;

  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf(''image'') !== -1) {
      const blob = items[i].getAsFile();

      const reader = new FileReader();
      reader.onload = function (event) {
        const base64 = event.target.result;
        const img = document.createElement(''img'');
        img.src = base64;
        imageContainer.appendChild(img);
      };
      reader.readAsDataURL(blob);
    }
  }
});

Codepen: Convert pasted image from clipboard to base64

👉 Drawbacks of Converting Image to Base64

Using Base64-encoded images in your code can be a useful technique for reducing the number of HTTP requests your website needs to make, which can improve page load times.

However, it’s worth noting that there are some drawbacks to using Base64-encoded images.

  • Base64-encoded images can increase the size of your HTML or CSS files. Since the image data is encoded as text, it takes up more space than the original binary data. This can increase your files’ size, slowing down page load times.
  • Base64-encoded images are not cached by the browser. When you use a regular image file, the browser can cache the file so that it doesn’t need to be downloaded again on subsequent page loads. However, since Base64-encoded images are embedded directly in your code, they cannot be cached in the same way.

Conclusion

converting an image to base64 in JavaScript is a useful technique that can be used for a variety of purposes, such as displaying images on a webpage, saving images to a database, or sharing images in a text format that preserves their original styling.

The basic process involves using the FileReader API to read the image data and convert it to a base64 string, which can then be used for further processing.

When converting an image to base64, it’s important to keep in mind that the resulting string can be quite long, so it may not be practical to use it for large images or when sending data over a network.

Additionally, some browsers may have limitations on the size of data that can be copied to the clipboard, so it’s important to test the code thoroughly across multiple browsers and platforms.

Overall, the ability to convert images to base64 in JavaScript provides a flexible and powerful tool for working with image data in web applications.

Thanks for Reading 🙏😇

Connect With Me 👇

https://linktr.ee/tusharkanjariya




Continue Learning