Richard C.
—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:
<img src="https://upload.wikimedia.org/wikipedia/commons/8/8e/Red-dot.svg" />
You embed the image into the HTML text like this:
<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.
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:
<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
:
<img src="data:image/jpeg;charset=utf-8;base64, ...
You can also use a Base64 image as a background in CSS:
<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.
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):
<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:
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:
$base64Text = base64_encode(file_get_contents($fileName));
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.
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.
<!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>
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.
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.
You need Base64 only when:
Below are some examples:
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.