How to Convert an Image to Base64 String in JavaScript

To convert an image to a Base64 string in JavaScript, you can use the FileReader object, which is available in modern browsers.

Here’s a step-by-step guide:

  1. Select an image: Use an input field of the type file to let the user select an image.
  2. Add Event Listener: Add an event listener for the change event on the input field. This will trigger the function to convert the image to a Base64 string when the user selects an image.
  3. Convert Image to Base64 String: Inside the event listener function, use the FileReader object to read the selected image as a Base64 string.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image to Base64</title>
</head>
<body>
 <input type="file" id="imageInput" />
 <script>
   document.getElementById('imageInput').addEventListener('change', function (event) {
   var file = event.target.files[0];
   if (file) {
     var reader = new FileReader();

     reader.onload = function (readerEvent) {
     var base64String = readerEvent.target.result;
     console.log(base64String);
   }
   reader.readAsDataURL(file);
   }
 });
 </script>
</body>
</html>

Output

Convert an Image to Base64 String in JavaScript

When you select an image using the input field, the Base64 string of the image will be logged to the console.

Converting an image selected from local to base64

To convert an image selected from the local filesystem to a Base64 string in a browser environment, choose an image from your local machine, and then it will display the image’s Base64 string in a textarea:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Convert Image to Base64</title>
</head>
<body>
  <input type="file" id="imageInput" />
  <textarea id="base64Output" rows="10" cols="50"></textarea>
  <script>
    document.getElementById('imageInput')
            .addEventListener('change', function (event) {
    var file = event.target.files[0];

    if (file) {
      var reader = new FileReader();

      reader.onload = function (readerEvent) {
      var base64String = readerEvent.target.result;
      document.getElementById('base64Output').value = base64String;
    }
    reader.readAsDataURL(file);
   }
 });
 </script>
</body>
</html>

Output

Convert an image selected from local to base64 in JavaScript

Converting the clipboard’s image data to base64

Converting an image from the clipboard to a Base64 string in a web environment requires a combination of the Clipboard API and the FileReader object.

Here’s how you do this:

  1. Add an event listener for the paste event on the window or a specific element.
  2. Extract the image from the clipboard data.
  3. Use the FileReader object to read the image as a Base64 string.
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clipboard Image to Base64</title>
</head>

<body>

  <button id="pasteButton">Paste Image from Clipboard</button>
  <textarea id="base64Output" rows="10" cols="50"></textarea>

  <script>
    document.getElementById('pasteButton').addEventListener('click', function () {
      navigator.clipboard.read().then(data => {
        for (let i = 0; i < data.items.length; i++) {
          if (data.items[i].type.startsWith('image/')) {
            const blob = data.items[i].getType('image/png');
            const reader = new FileReader();

           reader.onload = function (event) {
             document.getElementById('base64Output').value = event.target.result;
           };

          reader.readAsDataURL(blob);
          break;
        }
      }
   }).catch(err => {
      console.error("Error reading clipboard contents: ", err);
   });
 });
 </script>
</body>

</html>

Here’s a breakdown of the process:

  1. When the button is clicked, it triggers the navigator.clipboard.read() function to access the clipboard.
  2. The clipboard data is checked for image items.
  3. If an image item is found, it’s read as a Base64 string and displayed in the textarea.

Output

Converting the clipboard’s image data to base64

That’s it!