Question

How to Display Base64 Images in HTML

htmlimagebase64

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:

  1. data: — tells the browser this is an inline data URL
  2. image/jpeg — the MIME type of the file
  3. base64, — tells the browser the following content is Base64-encoded
  4. BASE64_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.

Take Quiz

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 = "iVBORw0KGgoAAAANSUhEUgAA...";
  const image = document.getElementById("preview");
  image.src = `data:image/png;base64,${base64}`;
</script>

Important detail

There should usually be no extra spaces inside the data URL:

src="data:image/jpeg;base64,LzlqLzRBQ..."

Not:

src="data:image/jpeg;base64, LzlqLzRBQ..."

That extra space can cause issues depending on the data and browser handling.

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:

  1. The browser reads the <img> tag.
  2. It sees the src value starts with data:.
  3. It understands this is not a file path or web URL.
  4. It reads image/png and knows the content should be treated as a PNG image.
  5. It reads base64, and knows the data is encoded in Base64.
  6. It decodes the Base64 string into binary image data.
  7. 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,${rawBase64}`;

  const logo = document.getElementById("logo");
  logo.src = dataUrl;
</script>

Execution flow:

  • rawBase64 stores the encoded image text
  • dataUrl combines the required prefix with the Base64 string
  • logo.src = dataUrl assigns the final image source
  • the browser decodes and displays the image

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 FileReader();

    reader.onload = () => {
      preview.src = reader.result;
    };

    reader.readAsDataURL(file);
  });
</script>

Here, FileReader.readAsDataURL() creates a valid data URL automatically.

Take Quiz

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>
  const img = document.getElementById("productImage");
  img.onerror = () => {
    img.src = "/images/fallback.png";
  };
</script>

Separating concerns

In larger codebases, the HTML stays simple while utility functions build the correct data URL.

function buildBase64ImageSrc(base64, type) {
  return `data:${type};base64,${base64}`;
}

This makes code easier to test and reuse.

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

Broken:

<img src="data:image/png,iVBORw0KGgo..." alt="Broken" />

Better:

<img src="data:image/png;base64,iVBORw0KGgo..." alt="Working" />

4. Using incomplete or corrupted Base64 data

If the string is truncated, the browser cannot decode the image.

5. Including comments or extra characters inside the src

Broken:

<img src="data:image/jpeg;base64,LzlqLzRBQ... <!-- Base64 data -->" alt="Broken" />

HTML comments do not belong inside the attribute value.

6. Assuming Base64 is always the best option

For large images, regular image files are often better because:

  • HTML stays smaller
  • browser caching works better
  • the page is easier to maintain

Comparisons

ApproachExampleBest forProsCons
Regular image URL/images/photo.jpgMost website imagesCacheable, clean HTML, smaller page sourceRequires separate request
Base64 data URLdata:image/png;base64,...Small inline assets, previews, self-contained pagesNo extra request, easy to embedLarger HTML, harder to read
Blob/Object URLblob:https://...Temporary browser-generated filesGood for local previews, efficient for uploaded filesNeeds JavaScript, temporary lifecycle

Base64 vs normal file path

  • Use normal file paths for most images on websites.
  • Use Base64 when embedding small images directly is genuinely helpful.

Base64 vs Blob URL

  • Base64 stores image data as text.
  • Blob URL points to browser-managed binary data.
  • Blob URLs are often better for large temporary files in interactive apps.
Take Quiz

Cheat Sheet

<!-- General format -->
<img src="data:MIME_TYPE;base64,BASE64_DATA" alt="Description" />

Common MIME types

  • image/jpeg
  • image/png
  • image/gif
  • image/svg+xml
  • image/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,
  • Append only the Base64 data after the comma
  • Avoid spaces and comments in the value

Quick JavaScript helper

function toDataUrl(base64, mimeType = "image/png") {
  return `data:${mimeType};base64,${base64}`;
}

Good default check

if (!base64 || typeof base64 !== "string") {
  throw new Error("Invalid Base64 image data");
}

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.

Take Quiz

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
Take Quiz

Keep learning

Related questions

View more