How to convert the image into a base64 string using JavaScript?

To convert an image into a base64 string using JavaScript, you can use the FileReader API for local files or combine XMLHttpRequest with FileReader for remote images. Base64 encoding represents binary image data as a text string, making it useful for embedding images directly in HTML or CSS.

Method 1: Converting Local Image Files

For user-uploaded files, use the FileReader API with an input element:

<!DOCTYPE html>
<html>
<body>
   <input type="file" id="imageInput" accept="image/*">
   <div id="result"></div>

   <script>
      document.getElementById('imageInput').addEventListener('change', function(e) {
         const file = e.target.files[0];
         if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
               const base64String = event.target.result;
               document.getElementById('result').innerHTML = 
                  '<p>Base64 String: ' + base64String.substring(0, 100) + '...</p>' +
                  '<img src="' + base64String + '" style="max-width: 200px;">';
            };
            reader.readAsDataURL(file);
         }
      });
   </script>
</body>
</html>

Method 2: Converting Remote Images

For images from URLs, combine XMLHttpRequest with FileReader:

<!DOCTYPE html>
<html>
<body>
   <div id="output"></div>

   <script>
      function imageToBase64(url, callback) {
         const xhr = new XMLHttpRequest();
         xhr.onload = function() {
            const reader = new FileReader();
            reader.onloadend = function() {
               callback(reader.result);
            };
            reader.readAsDataURL(xhr.response);
         };
         xhr.open('GET', url);
         xhr.responseType = 'blob';
         xhr.send();
      }

      // Convert image to base64
      imageToBase64('/html/images/logo.png', function(base64String) {
         document.getElementById('output').innerHTML = 
            '<p>Conversion completed!</p>' +
            '<p>Base64 preview: ' + base64String.substring(0, 50) + '...</p>' +
            '<img src="' + base64String + '" alt="Converted Image">';
      });
   </script>
</body>
</html>

Method 3: Using Canvas for Existing Images

Convert images already loaded in the DOM using HTML5 Canvas:

<!DOCTYPE html>
<html>
<body>
   <img id="sourceImage" src="/html/images/logo.png" alt="Source Image">
   <button onclick="convertImage()">Convert to Base64</button>
   <div id="canvasResult"></div>

   <script>
      function convertImage() {
         const img = document.getElementById('sourceImage');
         const canvas = document.createElement('canvas');
         const ctx = canvas.getContext('2d');
         
         canvas.width = img.width;
         canvas.height = img.height;
         
         ctx.drawImage(img, 0, 0);
         const base64String = canvas.toDataURL('image/png');
         
         document.getElementById('canvasResult').innerHTML = 
            '<p>Canvas conversion completed!</p>' +
            '<p>Base64 String: ' + base64String.substring(0, 100) + '...</p>';
      }
   </script>
</body>
</html>

Understanding Base64 Format

The FileReader API returns a data URL with this format:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...

To extract only the base64 string without the data URL prefix:

<!DOCTYPE html>
<html>
<body>
   <input type="file" id="fileInput" accept="image/*">
   <div id="base64Output"></div>

   <script>
      document.getElementById('fileInput').addEventListener('change', function(e) {
         const file = e.target.files[0];
         if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
               const dataUrl = event.target.result;
               const base64Only = dataUrl.split(',')[1]; // Remove data:image/jpeg;base64,
               
               document.getElementById('base64Output').innerHTML = 
                  '<p><strong>Full Data URL:</strong> ' + dataUrl.substring(0, 50) + '...</p>' +
                  '<p><strong>Base64 Only:</strong> ' + base64Only.substring(0, 50) + '...</p>';
            };
            reader.readAsDataURL(file);
         }
      });
   </script>
</body>
</html>

Common Use Cases

  • Embedding images directly in HTML/CSS without separate files
  • Storing image data in databases or local storage
  • Sending image data in JSON API requests
  • Creating offline-capable web applications

Conclusion

Use FileReader for local files, XMLHttpRequest + FileReader for remote images, or Canvas for DOM images. The FileReader API provides the most reliable method for converting images to base64 strings in JavaScript.

Updated on: 2026-03-15T23:18:59+05:30

672 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements