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 increase the page load time for smaller images by saving the browser from making additional HTTP requests.

Base64 encoding and Data URL 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, which are separated by a comma. The first part specifies a Base64 encoded image, and the second part specifies the Base64 encoded string of the image. Add also an alt attribute.

<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:

<!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>

Do you find this helpful?

Related articles