Skip to content

How to Display Base64 Images in HTML

Images encoded with Base64 can be embedded in HTML by using the <img> tag. This can help to reduce the page load time for smaller images by saving the browser from making additional HTTP requests.

Base64 encoding and Data URLs go hand-in-hand, as Data URLs reduce the number of HTTP requests that are needed for the browser to display an HTML document.

In this snippet, we’ll demonstrate how you can display Base64 images in HTML.

How to Use the <img> Tag

The <img> tag has a src attribute and contains the Data URL of the image. A Data URL is composed of two parts, separated by a comma. The first part specifies the MIME type (and optionally the character encoding), and the second part contains the Base64 encoded string of the image. Add also an alt attribute.

How to Display Base64 Images in HTML

html
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
  //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

Now, see the full code, where we need to place the <img> tag presented above within a <div> element.

Example of embedding a Base64 encoded image into HTML:

Example of embedding a Base64 encoded image into HTML

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <div>
      <p>From wikipedia</p>
      <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
        //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
    </div>
  </body>
</html>

Convert your image to a Base64 string

You can use the following code to convert any image on your device into a Base64 string.


html
<!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="inputImage" accept="image/*" />
  <textarea id="outputBase64" rows="10" cols="80" readonly></textarea>

  <script>
    document.getElementById('inputImage').addEventListener('change', function(event) {
      const file = event.target.files[0];
      const reader = new FileReader();

      reader.onloadend = function() {
          const base64 = reader.result;
          document.getElementById('outputBase64').value = base64;
      };

      reader.readAsDataURL(file);
    });
  </script>
</body>
</html>

Dual-run preview — compare with live Symfony routes.