Question
I am having trouble displaying a Base64-encoded image inline in HTML. How should this be done correctly?
<!DOCTYPE html>
<html>
<head>
<title>Display Image</title>
</head>
<body>
<img
id="base64image"
style="display: block; width: 100px; height: 100px;"
src="data:image/jpeg;base64,LzlqLzRBQ..."
alt="Base64 image"
/>
</body>
</html>
What is the correct format for displaying a Base64 image inside an <img> tag?
Short Answer
By the end of this page, you will understand how Base64 images are embedded in HTML using data URLs, what the correct src format looks like, when this approach is useful, and what common mistakes prevent the image from rendering.
Concept
A Base64 image in HTML is usually displayed through a data URL. A data URL lets you put the file contents directly inside the src attribute of an element such as <img>.
The general format is:
<img src="data:image/jpeg;base64,BASE64_DATA_HERE" alt="..." />
This string has three important parts:
data:— tells the browser this is an inline data URLimage/jpeg— the MIME type of the filebase64,— tells the browser the following content is Base64-encodedBASE64_DATA_HERE— the actual encoded image data
This matters because browsers need to know both:
- what kind of file they are decoding
- how the file data is encoded
If either part is wrong, the browser may fail to display the image.
Base64 encoding is useful when you want to embed small files directly into HTML, CSS, or JavaScript without making an extra network request. However, it also makes the HTML larger, so it is not always the best choice for bigger images.
Mental Model
Think of a normal image tag like giving the browser a home address:
<img src="/images/photo.jpg" />
The browser goes to that address and fetches the image.
A Base64 image is like putting the entire image inside the address label itself. Instead of telling the browser where to find the image, you hand the browser the image data directly.
So:
- file path = "Go fetch this image from somewhere"
- data URL = "Here is the image right now"
That is why the src starts with data: instead of a filename or URL.
Syntax and Examples
The basic syntax is:
<img src="data:image/png;base64,BASE64_STRING" alt="Inline image" />
JPEG example
<img
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."
alt="Inline JPEG"
width="100"
height="100"
/>
PNG example
<img
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
alt="Inline PNG"
/>
JavaScript example
If you receive Base64 data from an API, you can assign it dynamically:
<img id="preview" alt="Preview" />
<script>
const base64 = ;
image = .();
image. = ;
Step by Step Execution
Consider this example:
<img
id="avatar"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
alt="User avatar"
/>
Here is what happens step by step:
- The browser reads the
<img>tag. - It sees the
srcvalue starts withdata:. - It understands this is not a file path or web URL.
- It reads
image/pngand knows the content should be treated as a PNG image. - It reads
base64,and knows the data is encoded in Base64. - It decodes the Base64 string into binary image data.
- It renders the decoded image inside the page.
Small trace example with JavaScript
<img id="logo" alt="Logo" />
<script>
const rawBase64 = "iVBORw0KGgoAAAANSUhEUgAA...";
const dataUrl = `data:image/png;base64,`;
logo = .();
logo. = dataUrl;
Real World Use Cases
Base64 images are useful in several practical cases:
- Small icons embedded in HTML emails where external image loading may be limited
- Quick previews in web apps before uploading a file
- API responses that return image content as Base64
- Generated reports where a self-contained HTML file includes charts or logos
- Canvas exports where JavaScript converts drawings into data URLs
Example: preview uploaded image
<input type="file" id="fileInput" />
<img id="preview" alt="Preview" width="120" />
<script>
const input = document.getElementById("fileInput");
const preview = document.getElementById("preview");
input.addEventListener("change", () => {
const file = input.files[0];
const reader = new ();
reader. = {
preview. = reader.;
};
reader.(file);
});
Real Codebase Usage
In real projects, developers usually do more than simply place a Base64 string in HTML.
Common patterns include:
Validation before rendering
Make sure the string exists and is not empty.
if (!base64Image) {
console.error("No image data provided");
return;
}
Guard clauses for malformed data
Sometimes an API returns only the raw Base64 part, and sometimes it returns the full data URL.
function toImageSrc(value, mimeType = "image/png") {
if (!value) return "";
if (value.startsWith("data:")) return value;
return `data:${mimeType};base64,${value}`;
}
Fallback image handling
<img id="productImage" alt="Product" />
<script>
Common Mistakes
Here are common reasons Base64 images do not display:
1. Adding spaces in the data URL
Broken:
<img src="data:image/jpeg;base64, ABC123..." alt="Broken" />
Better:
<img src="data:image/jpeg;base64,ABC123..." alt="Working" />
2. Using the wrong MIME type
If the image is PNG but you label it as JPEG, rendering may fail.
Broken:
<img src="data:image/jpeg;base64,iVBORw0KGgo..." alt="Wrong type" />
Better:
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Correct type" />
3. Forgetting the base64, part
Comparisons
| Approach | Example | Best for | Pros | Cons |
|---|---|---|---|---|
| Regular image URL | /images/photo.jpg | Most website images | Cacheable, clean HTML, smaller page source | Requires separate request |
| Base64 data URL | data:image/png;base64,... | Small inline assets, previews, self-contained pages | No extra request, easy to embed | Larger HTML, harder to read |
| Blob/Object URL | blob:https://... | Temporary browser-generated files | Good for local previews, efficient for uploaded files | Needs JavaScript, temporary lifecycle |
Base64 vs normal file path
- Use normal file paths for most images on websites.
Cheat Sheet
<!-- General format -->
<img src="data:MIME_TYPE;base64,BASE64_DATA" alt="Description" />
Common MIME types
image/jpegimage/pngimage/gifimage/svg+xmlimage/webp
Examples
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="PNG image" />
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ..." alt="JPEG image" />
Rules
- Start with
data: - Include the correct MIME type
- Include
;base64,
FAQ
How do I show a Base64 image in HTML?
Use an <img> tag with a data URL:
<img src="data:image/png;base64,BASE64_DATA" alt="Image" />
Why is my Base64 image not displaying?
Common causes include a wrong MIME type, missing base64,, extra spaces, truncated data, or invalid characters in the string.
Can I use Base64 images in JavaScript?
Yes. You can assign a data URL to img.src directly:
img.src = `data:image/png;base64,${base64}`;
Is Base64 better than a normal image file?
Not usually. It is useful for small embedded assets, but regular image files are better for most website images because they are easier to cache and maintain.
Can I convert an uploaded file to Base64 in the browser?
Yes. FileReader.readAsDataURL() creates a data URL from the selected file.
Do I need the full data:image/...;base64, prefix?
Yes, unless the value you already have includes it. The browser needs that prefix to interpret the string correctly.
Mini Project
Description
Build a small image preview page that accepts a raw Base64 string and displays it in an <img> element. This demonstrates how to construct a valid data URL, validate the input, and render the image safely in the browser.
Goal
Create a page where a user can paste Base64 image data, choose an image type, and instantly preview the image.
Requirements
- Create a textarea for pasting Base64 image data
- Add a dropdown to select the MIME type
- Add a button that renders the image preview
- Show an error message if no Base64 data is provided
- Display the resulting image in an
<img>element
Keep learning
Related questions
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
CSS :not() Selector for Excluding a Class or Attribute
Learn how to use the CSS :not() selector to target elements that do not have a specific class or attribute, with examples and common mistakes.
Can HTML Checkboxes Be Readonly? Understanding readonly vs disabled in HTML Forms
Learn why HTML checkboxes do not support readonly, how disabled differs, and practical ways to prevent changes while still submitting values.