Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the complete data URL in an image element’s src attribute:

<img src="data:image/png;base64,BASE64_IMAGE_BYTES" alt="Description of the image">

For text-based SVG, percent-encode the SVG text instead of using Base64. Data URLs are best for small, one-off images. Larger or reused images normally belong in separate files because inline data increases HTML size, cannot be shared through a normal image cache, and may be rejected by your Content Security Policy (CSP).

The basic HTML syntax

A data URL follows this form:

data:[<mediatype>][;base64],<data>

The comma separates the metadata from the payload. In an HTML image, place the entire value in src:

<img
  src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1 1'%3E%3Crect width='1' height='1' fill='red'/%3E%3C/svg%3E"
  alt="Red square"
  width="32"
  height="32"
>

This example embeds a one-pixel SVG and gives it an accessible name, intrinsic display dimensions, and an explicit image media type. The media type should describe the actual bytes: use image/png for PNG bytes, image/jpeg for JPEG, image/gif for GIF, and image/webp for WebP. Omitting the media type invokes the data-URL default of text/plain;charset=US-ASCII, which is not an appropriate description for an image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Choose Base64 or percent-encoding

Base64 for binary image bytes

PNG, JPEG, GIF, and WebP files are binary. Convert their bytes to standard Base64, then prepend the matching type and ;base64,:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="Company logo">

The visible string above is abbreviated for illustration; a working URL must contain the complete Base64 payload. Use the standard Base64 alphabet expected by data URLs rather than substituting a URL-safe variant unless the consumer explicitly supports it. Do not add line breaks or accidentally copy the file’s binary bytes directly into HTML.

Percent-encoding for textual formats

SVG is text, so it can be placed after the comma with characters escaped for URL syntax. At minimum, escape characters that are not safe in a URL, including spaces, line breaks, percent signs where needed, angle brackets, quotes, and reserved delimiters. A compact SVG might look like this:

<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='40'%3E%3Ctext x='4' y='25'%3EHi%3C/text%3E%3C/svg%3E" alt="The word Hi">

Percent-encoding avoids Base64 overhead for small textual payloads, but it is less convenient when the SVG contains extensive styling or many special characters. Whichever representation you choose, the comma remains the boundary between metadata and data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate a data URL safely

  1. Obtain the exact bytes. Read the image as binary; do not decode it as text.
  2. Identify the format. Confirm that the declared MIME type matches the file’s actual format.
  3. Encode the payload. Base64-encode binary bytes, or percent-encode textual SVG.
  4. Assemble the prefix. Use data:image/<format>;base64, for Base64, or data:image/svg+xml, for escaped SVG text.
  5. Insert the whole value. Put it in src; do not split it across HTML attributes or append a conventional query string.
  6. Validate in a browser. Open the page with developer tools enabled and check the console and network information for CSP or decoding errors.

For production builds, let your bundler or asset pipeline generate data URLs only below a deliberately chosen size threshold. Keep the original image file available so it can be replaced or reused without editing a large HTML attribute by hand.

Accessibility still applies

The encoding in src does not change how assistive technology interprets the image. Write alt text that conveys the image’s purpose, not its file format. For example:

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

If the image is purely decorative, or its meaning is already fully provided by adjacent text, use an empty attribute:

<img src="data:image/svg+xml,%3Csvg ...%3E...%3C/svg%3E" alt="">

Do not omit alt altogether for a content image. The same width, height, responsive-sizing, and caption decisions apply to data-URL images as to file-backed images.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why a browser may block the image

Check the Content Security Policy

CSP controls which origins and schemes an image may load from. The img-src directive governs images and favicons. If img-src is absent, the browser falls back to default-src. A policy that does not permit the data: scheme can produce a console error and a broken image even when the URL is syntactically correct.

If your application intentionally uses data URLs, its policy needs an appropriate data: source in the image directive, for example:

Content-Security-Policy: default-src 'self'; img-src 'self' data:;

Whether to allow data: is a security decision. Add it only to the directive that needs it, rather than weakening unrelated script, style, or frame restrictions. Coordinate the change with the policy delivered by your server, framework, reverse proxy, or hosting platform.

Distinguish CSP errors from malformed data

  • CSP message: The console says the page refused a data resource. Fix the applicable img-src or default-src policy.
  • Decode or MIME message: The browser cannot parse the payload. Check the comma, Base64 padding, escaping, and media type.
  • Silent broken image: Inspect the final rendered src in developer tools; templating may have truncated or HTML-escaped the value incorrectly.

Data-URL limits and performance trade-offs

RFC 2397 describes the scheme as useful for short values. Base64 commonly makes a payload larger than the original binary, and the resulting characters become part of the HTML document. A large inline image therefore increases document transfer and parsing work instead of being fetched, cached, and updated as an independent resource.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Use an inline data URL when… Use a normal image URL when…
The image is small and used once, such as a tiny icon in a generated fragment. The image is large, reused across pages, or likely to change independently.
You need a self-contained HTML artifact and accept the larger document. You want browser caching, CDN delivery, responsive variants, or simple replacement.
Your CSP explicitly permits the data: scheme for images. Your security policy forbids data sources or you cannot change it.

There is no single portable browser-wide maximum length. Limits vary by browser, embedding context, server, and other layers in the delivery path. Treat historical attribute-length figures as historical, not as a guarantee for current browsers. If the image approaches a size that makes the page noticeably larger, store it as a separate file.

Common mistakes and fixes

Missing the media type

Symptom: The image is not decoded or is treated as plain text.
Fix: Start with an explicit type such as data:image/png;base64, or data:image/svg+xml,.

Using a file path after data:

Symptom: You write data:image/png,logo.png and expect the browser to read a local file.
Fix: The data portion is the actual encoded content. Read the file and encode its bytes, or use a normal relative or absolute URL.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Forgetting the comma

Symptom: The browser reports an invalid URL.
Fix: Include exactly one separator comma between metadata and payload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encoding text as binary, or binary as text

Symptom: The image is corrupted after conversion.
Fix: Base64-encode raw binary bytes. For SVG text, percent-encode the text and ensure characters such as #, %, quotes, and whitespace are handled correctly.

Adding a query string

Symptom: A suffix such as ?v=2 does not create a cache-busting variant.
Fix: A data URL has no relative URL form, and its data portion is opaque. Change the payload itself or use a conventional URL where query parameters are meaningful.

Embedding untrusted content

Symptom: You assume data URLs make arbitrary input safe.
Fix: Validate and encode untrusted data. An image element must load an image resource, and executable code embedded in an image resource must not run, but data URLs do not bypass CSP or make unsafe input trustworthy. Never treat a data URL as a general-purpose sanitization mechanism.

Testing checklist

  • Confirm the final string begins with data: and contains a comma.
  • Verify the declared media type against the file’s actual format.
  • For Base64, check that the complete payload copied into HTML has not been truncated or wrapped with unintended whitespace.
  • For SVG, percent-encode reserved characters and test both XML parsing and URL parsing.
  • Inspect the browser console for img-src or default-src violations.
  • Test with JavaScript disabled if the image is expected to work in a static document.
  • Measure the resulting HTML size and compare it with a separately cached image file.
  • Provide useful alt text, or alt="" when the image is decorative or redundant.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your actual goal is to capture a web page as an image rather than hand-construct an HTML data URL, ScreenshotNeo returns a screenshot from one GET request. It accepts cookie and consent banners like a visitor, removes more than 60 known consent platforms along with newsletter popups and chat widgets before capture, and reports whether a response was billed. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

See the parameter reference and authentication details in the ScreenshotNeo documentation. cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Every plan includes its features; the Free plan provides 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account to try it.

When to replace a data URL

Move the image to a normal URL when it is reused, substantial in size, updated independently, needed in multiple responsive resolutions, or disallowed by CSP. Keep a data URL when its small size and self-contained nature outweigh those costs—for example, a tiny generated SVG in a standalone HTML email or an isolated test fixture. The HTML syntax is the same either way; only the resource location changes.

Frequently Asked Questions

Can I use a data URL in CSS instead of HTML?

Yes, data URLs can be used in CSS image-valued properties, but the CSS policy and escaping rules still apply. This article’s accessibility guidance specifically concerns an HTML img element, where you can provide alt text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does Base64 encryption protect an embedded image?

No. Base64 is an encoding, not encryption. Anyone who can read the HTML can decode the image bytes.

Can a data URL be loaded from a separate file with a relative path?

No. The payload is contained in the URL itself. Use a normal relative URL if the image should be loaded from another file.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.