DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
Base64

How to Use HTML Image Data URLs (with Base64, SVG, CSP, and Size Guidance)

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">

Use data:image/...;base64, for binary image bytes, or percent-encode text such as SVG. Keep the payload small, provide useful alt text, and check your Content Security Policy (CSP) if the browser refuses to load it.

The HTML syntax

A data URL follows this form:

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

The comma separates metadata from the payload. For an image, declare the actual media type, then place the entire URL 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 SVG text without Base64. The HTML img element is intended for one image resource; the representation used in src does not change normal accessibility requirements. The original syntax is defined by RFC 2397, while the living HTML Standard defines image-element behavior.

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

Binary image example

For PNG, JPEG, GIF, WebP, or another binary format, use standard Base64:

<img
  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB..."
  alt="One-pixel transparent image"
  width="1"
  height="1"
>

The shortened bytes above are illustrative only; a browser needs the complete Base64 representation. Match the media type to the bytes. For example, JPEG bytes require image/jpeg, not image/png.

Base64 or percent-encoding?

Use Base64 for binary bytes

Base64 converts arbitrary bytes into text that can travel inside an HTML attribute. A typical value is:

data:image/webp;base64,UklGR...
  • Keep the ;base64, marker; without it, the browser interprets the payload as non-Base64 data.
  • Use standard Base64, including its normal padding characters when present. URL-safe Base64 substitutions are not automatically interchangeable.
  • Do not insert line breaks or surrounding quotation marks into the payload.

Use percent-encoding for textual SVG

SVG is text, so it can be embedded without ;base64 when characters that are unsafe in a URL are escaped:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='40'%3E%3Ctext x='4' y='25'%3EHello%3C/text%3E%3C/svg%3E

Spaces, line breaks, percent signs, quotes, angle brackets, and other reserved or non-printing characters may need percent-encoding. The exact payload is opaque to URL processing; encode it deliberately rather than pasting unescaped markup into a complex attribute.

Why the comma matters

Everything before the first comma describes the media type and optional encoding. Everything after it is the data. A missing comma, a second accidental prefix, or a copied value such as data:image/png;base64,data:image/png... makes the resource invalid.

Creating data URLs safely

Browser-side JavaScript for a selected file

This small page reads a local file and displays it as a data URL. It does not upload the file:

<input id="file" type="file" accept="image/*">
<img id="preview" alt="Selected image preview">
<script>
  const fileInput = document.querySelector('#file');
  const preview = document.querySelector('#preview');

  fileInput.addEventListener('change', () => {
    const file = fileInput.files[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
      preview.removeAttribute('src');
      return;
    }
    const reader = new FileReader();
    reader.addEventListener('load', () => {
      preview.src = reader.result;
    });
    reader.readAsDataURL(file);
  });
</script>

For production interfaces, consider rejecting unexpectedly large files before reading them and preserving the original MIME type supplied by the file object only after validating the content your application accepts.

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

Python: convert a local image

from pathlib import Path
import base64

path = Path("logo.png")
mime = "image/png"
payload = base64.b64encode(path.read_bytes()).decode("ascii")
data_url = f"data:{mime};base64,{payload}"
print(data_url)

Node.js: convert a local image

import { readFileSync } from "node:fs";

const bytes = readFileSync("logo.png");
const dataUrl = `data:image/png;base64,${bytes.toString("base64")}`;
console.log(dataUrl);

Shell/cURL pipeline

On systems with the standard base64 utility, this prints a PNG data URL. The exact wrapping options differ between platforms, so ensure the output has no line breaks:

printf 'data:image/png;base64,'
printf 'logo.png' | base64 | tr -d 'n'
printf 'n'

cURL itself transports bytes; it does not decide the correct media type or create a data URL automatically. Validate both pieces before inserting the result into HTML.

Accessibility and valid HTML

Write replacement text in alt

Describe the image’s purpose, not its encoding. For an account avatar, use a person’s name; for a chart, summarize the useful result. A data URL does not make an image exempt from accessibility rules.

<img src="data:image/svg+xml,..." alt="Green check mark">

Use an empty value for decorative art

If nearby text already conveys the image’s meaning or the image is purely decorative, use alt="". Do not omit the attribute: omission can cause assistive technology to announce the file or URL instead of treating it as decorative.

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

Reserve dimensions when layout stability matters

Adding width and height (or an equivalent aspect-ratio rule) lets the browser reserve space before decoding the embedded bytes. This is especially useful when several inline images appear together.

When a data URL is the wrong choice

Situation Prefer Reason
One tiny icon used once Data URL No separate request is needed and the markup stays manageable.
Large photograph, hero image, or screenshot Normal image URL Base64 increases the textual size and makes the HTML document heavier.
Same image appears on many pages Normal image URL A separate resource can be cached and reused without duplicating bytes in every document.
Image changes independently of page markup Normal image URL Updating a file is simpler than regenerating many documents.
Strict CSP that excludes data: Hosted image or an explicitly reviewed policy change The browser will enforce the policy even when the data URL is syntactically correct.

RFC 2397 describes data URLs as useful for short values. Base64 is also larger than the original binary representation, and browser maximum URL lengths vary. There is no portable, browser-wide “maximum image data URL” number to design around; test the actual browsers and document sizes you support.

Fixing a blocked or broken image

1. Inspect the console and response policy

A CSP violation normally appears in the browser developer console. The img-src directive controls permitted image and favicon sources. If img-src is absent, the browser falls back to default-src. A policy such as:

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
Content-Security-Policy: default-src 'self'

does not permit a data URL for images. If your security review allows it, add the scheme only to the image directive:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Content-Security-Policy: default-src 'self'; img-src 'self' data:

Do not add data: broadly to script-src, object-src, or unrelated directives. Follow the site’s security policy and test the change in a report-only policy first when appropriate. A CSP reference is available from MDN’s Content Security Policy documentation.

2. Check the prefix and payload

  • Confirm the value begins with data: and contains exactly one metadata/payload comma.
  • Use a real image MIME type such as image/png, image/jpeg, image/gif, image/webp, or image/svg+xml.
  • For binary bytes, confirm ;base64, is present and that the Base64 string was not URL-decoded, truncated, or wrapped with whitespace.
  • For SVG text, percent-encode markup characters and ensure the XML is well formed.

3. Check the HTML parser context

Use quoted attributes when the URL contains punctuation. Server-side templating, JSON serialization, or a sanitizer may escape, truncate, or remove the value. Inspect the final DOM in developer tools rather than only the source template.

4. Check the image bytes

Download or decode the payload independently and open the resulting file. A correct prefix cannot repair corrupted bytes or a file whose content is not the declared type. An img element must not load a non-image resource as an image.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Security and URL behavior

Data URLs are not a way to bypass security controls. Modern browsers treat navigated data URLs as unique opaque origins, and top-level navigation to them is restricted as a security mitigation. Do not put untrusted, unsanitized user input into an SVG data URL: although an image resource is not supposed to execute embedded code as script, unsafe markup can still create parsing, spoofing, or denial-of-service problems in surrounding systems. Sanitize untrusted content and enforce CSP.

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

A data URL has no relative-URL form. Appending ?version=2 does not create a normal query string for cache-busting; the data portion is opaque. If you need independent cache keys, access control, or content negotiation, use a normal URL served by your application or a CDN.

Or skip the browser setup

If what you actually need is a clean screenshot of a web page rather than an inline image assembled by hand, ScreenshotNeo returns PNG, JPEG, WebP, or PDF from one request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status.

Use the API documentation at https://screenshotneo.com/docs/ for all options:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
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 provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Sign up free.

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

Practical checklist

  • Start with <img src="data:..." alt="...">.
  • Declare the actual image media type.
  • Use Base64 for binary bytes and percent-encoding for textual SVG.
  • Keep the payload short and avoid duplicating large or frequently reused images.
  • Give informative alt text, or alt="" for decorative art.
  • Check img-src and its default-src fallback when CSP blocks the image.
  • Inspect the final DOM and independently decode suspicious payloads.

Frequently Asked Questions

Can I use a data URL in an image’s srcset?

Yes, but each candidate must be a complete, correctly escaped URL and the commas used by srcset descriptors make maintenance difficult. A normal image URL is usually clearer for responsive images.

Does omitting the media type make an image work?

The data URL default is text/plain;charset=US-ASCII, not an image type. Always declare the image media type explicitly.

Can I add a cache-busting query string to a data URL?

No. A data URL has no relative URL form, and its payload is opaque; use a separate resource URL when you need normal query parameters or cache control.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.