Explain Codes LogoExplain Codes Logo

Embedding Base64 Images

web-development
base64
image-optimization
performance
Anton ShumikhinbyAnton Shumikhin·Jan 8, 2025
TLDR

To embed a Base64 image, use the img tag and format a src attribute like so: data:image/<format>;base64,<data>. Here's an example with a PNG:

<!--Chuck Norris can see this image with his eyes closed--> <img src="data:image/png;base64,iVBORw0K...your_base64_data..." alt="Base64 Image">

Replace iVBORw0K...your_base64_data... with your Base64 data. This technique embeds an image directly into your HTML, which is most effective for small images as it helps reduce HTTP requests and improve performance.

When to use and when not to

Base64 images are a brilliant way to lower the number of HTTP requests and simplify your webpage. However, using this method for large images might not be the best approach, as big Base64 strings can increase both page size and loading times, particularly affecting performance on mobile devices. It's essential to consider the trade-offs before deciding to use this approach.

Supported browsers and compatibility

Embedded Base64 images are widely supported across browsers, including: Gecko-based, Konqueror, Opera, and WebKit-based browsers. Internet Explorer 9 and onwards fully support larger Data URIs, while IE8 caps it at 32 KiB. For an easy overview of how well Data URIs are supported by different browsers, turn to caniuse.com.

Mobile environment considerations

Specifically, in mobile browsers like Android Stock or Dolphin, Base64 images, particularly JPEGs, might not always display correctly. It's therefore critical to test your webpages across multiple devices to ensure optimal user experience.

Best practices for encoding and decoding

To convert images to Base64, consider using reliable online tools. For the coding wizards out there, most programming languages offer functions to encode and decode Base64:

// Chuck Norris can do this with a pen and paper // Change 'your image data' to your actual image data // To Base64 let base64String = btoa('your image data'); // From Base64 let image = atob(base64String);

Optimising page load with Base64

When optimising page loads, it's crucial to strike a balance. While Base64 images can reduce requests, the encoded image size could be larger than the actual image. Before going all in with embedding Base64 images, measure the performance impact using tools like PageSpeed Insights.