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

A Base64 image URL is a data: URL that puts an image’s encoded bytes directly in an attribute such as src. The dependable pattern is data:image/png;base64,ENCODED_BYTES: the MIME type identifies the image format, ;base64 says how the payload is encoded, and the comma separates the metadata from the data. For example, this complete 1×1 GIF is valid HTML:

<img src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==' alt='One-pixel example'>

Replace the payload with Base64 generated from your own image bytes, and keep the MIME type matched to the actual file. The sections below show how to generate, embed, validate, decode, and decide whether an inline image is appropriate.

How the Base64 image URL syntax works

The formal data-URL structure is data:[<media-type>][;base64],<data>. RFC 2397 documents this scheme and its use in an HTML IMG element (RFC 2397). MDN’s current reference explains the same parts and common authoring errors (MDN data: URLs).

Part Example Purpose
Scheme data: Declares that the URL contains data rather than pointing to a separate resource.
Media type image/png Describes the format the browser should decode. Common values include image/png, image/jpeg, image/gif, image/webp, and image/svg+xml.
Encoding flag ;base64 Tells the browser that the following characters are Base64-encoded bytes.
Separator , Marks where metadata ends and the encoded payload begins.
Payload R0lGODlh... The complete Base64 representation of the image file.

If you omit the media type, the default is text/plain;charset=US-ASCII, not an image. A missing comma, a wrong MIME type, or a payload that is not actually Base64 will produce a broken image or unexpected behavior.

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.
#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

Complete HTML examples

A tiny, complete GIF

This is a real, self-contained one-pixel GIF rather than a placeholder. You can paste it into a blank HTML document and open it in a browser:

<!doctype html>
<html lang='en'>
<meta charset='utf-8'>
<title>Inline image</title>
<img width='1' height='1' alt='One-pixel transparent example'
     src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='>
</html>

The width, height, and alt attributes are ordinary HTML; they are not part of the data URL.

Using a PNG payload

A PNG data URL has the same structure:

<img alt='Chart thumbnail' src='data:image/png;base64,PASTE_THE_COMPLETE_PNG_BASE64_HERE'>

The text shown as PASTE_THE_COMPLETE_PNG_BASE64_HERE is intentionally not an image. A browser needs the complete output from a Base64 encoder, with no explanatory words, Markdown backticks, or line-break characters inserted into the attribute.

CSS and JavaScript forms

Data URLs can be used anywhere an image URL is accepted. In CSS:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.badge {
  background-image: url('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==');
}

In JavaScript:

const pixel = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
document.querySelector('#preview').src = pixel;

Generate a data URL from an image file

Command line on macOS or Linux

Encode the bytes, then prepend the correct media type. The base64 command differs slightly between systems, so remove line wrapping explicitly where your implementation supports it:

encoded=$(base64 < logo.png | tr -d 'n')
printf 'data:image/png;base64,%sn' "$encoded"

For a JPEG, change both the input file and the prefix to image/jpeg. Do not infer the type from the filename alone if the file may have been renamed; the prefix must describe the bytes that a decoder will receive.

PowerShell on Windows

$bytes = [System.IO.File]::ReadAllBytes('logo.png')
$encoded = [Convert]::ToBase64String($bytes)
"data:image/png;base64,$encoded"

To save the result as a text file:

[IO.File]::WriteAllText('logo-data-url.txt', "data:image/png;base64,$encoded")

Python

from base64 import b64encode
from pathlib import Path
import mimetypes

path = Path('logo.png')
mime, _ = mimetypes.guess_type(path.name)
if mime is None or not mime.startswith('image/'):
    raise ValueError('Use an image file with a known image MIME type')

payload = b64encode(path.read_bytes()).decode('ascii')
data_url = f'data:{mime};base64,{payload}'
print(data_url)

Python’s encoder returns ASCII characters. Reading in binary mode (as read_bytes() does) is important; opening an image as text can corrupt its bytes.

Node.js

import { readFileSync } from 'node:fs';

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

Use image/jpeg, image/gif, or another matching type when the input format changes.

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

In a browser with a file picker

FileReader.readAsDataURL() creates the complete prefix and payload for a user-selected file:

<input id='file' type='file' accept='image/*'>
<img id='preview' alt='Selected image preview'>
<script>
  const input = document.querySelector('#file');
  const preview = document.querySelector('#preview');
  input.addEventListener('change', () => {
    const file = input.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.addEventListener('load', () => { preview.src = reader.result; });
    reader.readAsDataURL(file);
  });
</script>

The browser chooses a media type from the selected file. Validate the file type and size before displaying or storing user uploads.

Embed the result safely and correctly

Keep the entire URL in one attribute value

Do not insert spaces, newlines, quotes, or HTML markup into the payload. If you generate HTML programmatically, use an HTML serializer or escape the attribute value rather than concatenating untrusted text into markup.

Use meaningful alternative text

Base64 changes how an image is transported, not how it is experienced. Provide useful alt text for informative images and an empty alt for decorative ones.

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

Check the MIME type against the file signature

A URL beginning with image/png does not convert a JPEG into a PNG. If the bytes and declared type disagree, browsers may refuse to render the image or handle it inconsistently. Generate the prefix from a trusted type check when files come from users.

Do not confuse encoding with encryption

Base64 is reversible representation. Anyone who can read the HTML can decode the image, so it does not provide privacy, access control, or protection from inspection.

Decode a data URL back into an image

To recover a file, split at the first comma, decode the part after it, and write the resulting bytes.

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
from base64 import b64decode
from pathlib import Path

url = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='
header, encoded = url.split(',', 1)
if ';base64' not in header or not header.startswith('data:image/'):
    raise ValueError('Not a Base64 image data URL')
Path('decoded-image.gif').write_bytes(b64decode(encoded, validate=True))

The validate=True check rejects characters that do not belong to a correctly formatted Base64 payload.

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

When inline Base64 is a good choice

Situation Inline data URL Separate image URL
Small icon needed inside one self-contained HTML or email file Convenient: no additional request or asset file is required. Requires shipping and resolving another resource.
Large photograph, hero image, or many repeated images Makes every copy of the document larger and harder to cache independently. Usually easier to cache, replace, and serve through an image pipeline.
Image shared by many pages Duplicates the encoded bytes in each document. One URL can be cached and reused.
Strict browser or security policy Check the project’s Content Security Policy and browser behavior first. Often fits an existing image-source policy more naturally.

RFC 2397 describes data URLs as suitable for small inline images and cautions that larger images are likely inappropriate. There is no single browser-mandated maximum length: limits vary by browser and implementation. MDN documents current browser-specific limits, so verify the target browsers rather than adopting an invented universal threshold.

Performance and security considerations

Document size and caching

Base64 represents three bytes using roughly four encoded characters, before the data:image/...;base64, prefix. The practical cost is not only that expansion: the encoded bytes become part of every HTML, CSS, or JSON document that contains them. A separate image can be cached, replaced, and requested independently; an inline copy is downloaded again whenever its containing document is downloaded.

Opaque origins and navigation

MDN notes that browsers treat data: URLs as unique opaque origins. Modern browsers also block top-level navigation to data URLs as a mitigation for security issues. RFC 2397 says the embedded media type’s own security considerations still apply. Therefore, Base64 does not make an image inherently safe, and you should not use a data URL as a way to bypass origin or content-security rules.

Content Security Policy

If an image appears as broken despite a valid payload, inspect the browser console for a Content Security Policy violation. A policy must permit data images (commonly through an appropriate img-src directive) for this technique to work. Change policy deliberately; do not weaken it broadly just to hide an error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 what you really need is a current screenshot of a web page to embed or process, ScreenshotNeo returns an image from one GET request. It is a screenshot API and MCP server, not a Base64 encoder; after downloading the image, you can Base64-encode that file with one of the commands above.

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)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

See the ScreenshotNeo documentation for parameters and response details. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

Troubleshooting broken image data URLs

The browser shows a broken-image icon

  • Confirm the value starts with data: and contains a comma after the metadata.
  • Confirm ;base64 is present and the payload was produced from binary bytes.
  • Compare the declared MIME type with the original file format.
  • Remove accidental Markdown fences, quotes surrounding the whole URL, spaces, and line breaks.

The image works in one browser but not another

  • Check each target browser’s data-URL length limit; there is no universal maximum.
  • Inspect developer-console errors for CSP restrictions.
  • Try a small known-good payload, such as the 1×1 GIF above, to separate syntax problems from size or policy problems.

The generated string is enormous

That is expected for a large source image or a document containing many inline copies. Resize or compress the source, inline only small critical assets, or move the image to a separately hosted URL.

The decoded file will not open

  • Split only at the first comma; commas in later data are payload content.
  • Use a strict Base64 decoder and check for truncated output.
  • Write decoded bytes in binary mode, never as text.
  • Open the file header with an image tool to verify that the bytes match the declared format.

Quick validation checklist

  1. Start with data:.
  2. Declare the correct image MIME type.
  3. Include the literal ;base64 flag.
  4. Include exactly one metadata/data separator comma.
  5. Paste the complete encoder output with no placeholder text.
  6. Keep the URL within the size limits of every target browser and document format.
  7. Check CSP and provide appropriate alt text.

Frequently Asked Questions

Can I use a Base64 image URL in an email?

Many email clients support small data-URL images, but client-specific filtering and size limits vary. Test the exact clients you support and consider an approved hosted-image method for larger assets.

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

Does Base64 reduce an image’s file size?

No. Base64 is an encoding, not compression; the textual representation is generally larger than the original binary bytes.

Can I put a Base64 URL in an ordinary hyperlink?

The URL syntax can be placed in an href, but modern browsers restrict top-level navigation to data URLs. Use it for an image source or another narrowly defined embedded-resource case instead.

Is an SVG data URL encoded the same way?

Yes when you choose Base64: use data:image/svg+xml;base64, followed by the encoded SVG bytes. The declared type must match the content, and the same size and security considerations apply.

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.