Sentry Answers>HTML>

How do I display a Base64 image in HTML?

How do I display a Base64 image in HTML?

Richard C.

The Problem

If you want to embed an image directly into an HTML file’s code, instead of linking to an image file, and you don’t have access to JavaScript, then encoding the image as Base64 is the only solution.

In other words, instead of linking an image like this:

Click to Copy
<img src="https://upload.wikimedia.org/wikipedia/commons/8/8e/Red-dot.svg" />

You embed the image into the HTML text like this:

Click to Copy
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />

This article will explain how to convert an image to Base64 and how to add it to your page correctly. But please read to the end of the article to see alternatives, because Base64 is inefficient and very rarely necessary.

The Solution

First, you need to convert your image to Base64, and then add it to the HTML.

To manually convert an image, use a site like http://base64online.org/encode. Upload your image to the site and copy the text it returns.

Here’s an HTML example using a tiny image from Wikipedia that was converted to Base64:

Click to Copy
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== " />

Your src attribute must begin with data:image/png;base64,. After that, you need to insert your image text, which can be surrounded on both sides by as much whitespace as you like.

The png can be replaced with the MIME type of your file: jpeg, gif, or svg+xml.

Some browsers might fail to display your image if you use an unexpected text encoding. To be safe, always specify your MIME Content-Type and Content-Encoding:

Click to Copy
<img src="data:image/jpeg;charset=utf-8;base64, ...

You can also use a Base64 image as a background in CSS:

Click to Copy
<div style=" width: 10px; height: 10px; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==) no-repeat;"> A dot. </div>

A common error reported by programmers is mistakenly double-encoding their images. If you encounter an error you can’t debug, try to decode your Base64 text to check that you didn’t encode it twice accidentally.

Encode An Image Programmatically

Instead of using a tool to encode your image, you can do it with JavaScript (and of course on the server in PHP or Python or other languages):

Click to Copy
<div id="imageContainer"></div> <script> async function addImage() { const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png'; const response = await fetch(imageUrl); const imageBlob = await response.blob(); const reader = new FileReader(); reader.readAsDataURL(imageBlob); // Converts the blob to base64 reader.onloadend = function() { const imageElement = new Image(); imageElement.src = reader.result; imageElement.width = 50; document.getElementById('imageContainer').appendChild(imageElement); } } addImage(); </script>

However, if you have access to both the file and JavaScript, there is no reason to use embedded Base64. Rather use createObjectURL, as discussed later.

The btoa() function (Binary To ASCII Base64) in JavaScript is used more for strings than image embedding:

Click to Copy
const encodedData = btoa("Hello, world"); // encode a string const decodedData = atob(encodedData); // decode the string

If you’re working with strings instead of images, note that btoa() won’t work with Unicode, because the function defines binary data as “strings in which the code point of each character occupies only one byte”.

In PHP, you can use:

Click to Copy
$base64Text = base64_encode(file_get_contents($fileName));

When Not To Use Base64 Images

Base64 is a string filled with groups of four 6-bit characters (A-Z, a-z, 0-9). An image in Base64 is always at least a third larger than a binary image file. Your users’ CPUs need to do extra work to decode the image, making your HTML code longer and more difficult to maintain. For these reasons, you should avoid using Base64 whenever there is another solution.

File Uploads

For instance, don’t use Base64 to display an image on the page after a user has uploaded or selected an image from their computer. If your page has access to JavaScript and the internet, you should rather use createObjectURL.

Here’s an example that creates a blob from a file, creates a temporary URL pointing to the blob (automatically handled by the browser), and adds it as an image to the document. When handling a user’s uploaded file you would create a blob from that, instead of a file on the web.

Click to Copy
<!DOCTYPE html> <html lang=""> <body> <div id="imageContainer"></div> <script> async function addImage() { const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png'; const response = await fetch(imageUrl); const imageBlob = await response.blob(); const objectURL = URL.createObjectURL(imageBlob); const imageElement = new Image(); imageElement.src = objectURL; imageElement.width = 50; document.getElementById('imageContainer').appendChild(imageElement); } addImage(); </script> </body> </html>

CORS Errors

You might have a CORS error if you try to load an image from a different domain onto your canvas element and then try to manipulate that image. While Base64 can prevent this error, you should use createObjectURL for this problem too. Since the temporary URL created from the blob will be on your domain, it won’t encounter security problems.

Books

Both EPUB files and Jupyter notebooks can link to images as local files kept with the book. You do not need to insert the images as Base64.

When To Use Base64 Images

You need Base64 only when:

  • The browser might block image loading.
  • You have no access to JavaScript.
  • You have no Internet access.
  • You cannot include images with your offline HTML file.

Below are some examples:

  • Creating an offline, standalone, single-file HTML report.
  • Email software can block external image links in HTML emails. Using Base64 images will ensure your email is displayed as intended.
  • Syntax.fmListen to the Syntax Podcast
  • ResourcesWhat is Distributed Tracing
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.