While creating an HTML document, you can include images in various ways. These can be using external image URLs, local images, and base64 images. When we embed an image in the HTML document, it means that it becomes part of the HTML file. So, embedding it as base64 content reduces the HTTP requests. The HTML “<img>” tag can be utilized to embed Base64-encoded images.
In this write-up, you will learn how Base64 images are displayed in HTML.
How to Add 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>
Conclusion
There are three main methods to embed images in HTML that are local directories, external URLs, and adding base64 images. The base64 encoded images are beneficial in a way that by including these to HTML documents reduces the HTTP requests needed for the browser. To embed the base64 image, use the HTML “<img>” tag along with the “src” attribute that specifies the base64 encoded string. This post has explained the procedure to show base64 images in HTML.
Leave a Comment