How to Convert Image to Base64 with Javascript

To convert an image to Base64 using JavaScript, you can follow these steps:


1. Load the image using JavaScript.

2. Convert the image to a Base64 string.

3. Use the Base64 string as needed, such as displaying it in an `<img>` tag or sending it to a server.


Here's an example of how you can achieve this:


<!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="fileInput" accept="image/*">

  <img id="imagePreview" src="" alt="Image Preview">


  <script>

    // Function to convert image to Base64

    function imageToBase64(file) {

      return new Promise((resolve, reject) => {

        const reader = new FileReader();

        reader.onload = () => resolve(reader.result);

        reader.onerror = reject;

        reader.readAsDataURL(file);

      });

    }


    // Event listener for file input change

    document.getElementById('fileInput').addEventListener('change', async (event) => {

      const file = event.target.files[0];

      if (file) {

        try {

          const base64String = await imageToBase64(file);

          document.getElementById('imagePreview').src = base64String;

          console.log('Base64 string:', base64String);

        } catch (error) {

          console.error('Error converting image to Base64:', error);

        }

      }

    });

  </script>

</body>

</html>


This HTML file provides an input element (`<input type="file">`) for selecting an image file. When an image file is selected, it reads the file using `FileReader` and converts it to a Base64 string. Finally, it displays the image preview using an `<img>` tag and logs the Base64 string to the console.