Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
Base64

How to Embed a PNG as Base64 in HTML (Data URLs, FileReader, and Fixes)

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

Embed a PNG in HTML by placing its Base64 bytes in a data: URL:

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

The image/png media type identifies the file, ;base64 says the payload is encoded, and the comma separates that declaration from the encoded bytes. For a file chosen by a user, the safest browser-native conversion is FileReader.readAsDataURL().

The data URL format

RFC 2397 defines the inline URL grammar as data:[<media-type>][;base64],<data>. A PNG image therefore uses:

data:image/png;base64,ENCODED_PNG_BYTES

Use that entire value as the src of an image. The comma is required; without it, the browser cannot reliably distinguish the metadata from the payload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Part Purpose PNG example
data: Identifies a data URL. data:
Media type Tells the browser what the bytes represent. image/png
;base64 Declares that the following data is Base64 text. ;base64
Comma Separates the declaration from the encoded payload. ,
Payload The PNG file’s encoded bytes. iVBORw0KGgo...

Keep meaningful alternative text in alt. Base64 does not make an image accessible by itself; the surrounding HTML still needs an appropriate text alternative.

Convert a selected PNG in the browser

FileReader.readAsDataURL() accepts a Blob or File and, when reading finishes, places a complete data URL in reader.result. This single HTML file lets someone choose a PNG and immediately preview it:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>PNG Base64 preview</title>
</head>
<body>
  <label for="pngFile">Choose a PNG</label>
  <input id="pngFile" type="file" accept="image/png">
  <img id="preview" alt="Selected PNG preview">

  <script>
    const input = document.querySelector('#pngFile');
    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.addEventListener('error', () => {
        console.error('Could not read the selected file.');
      });
      reader.readAsDataURL(file);
    });
  </script>
</body>
</html>

What happens in this example

  1. The accept="image/png" hint filters the file picker toward PNG files. It is a user-interface hint, not a security boundary, so validate the file again if the upload will be sent to a server.
  2. The change event runs after a selection. If the user cancels, input.files[0] is absent and the handler returns.
  3. readAsDataURL(file) reads the binary file asynchronously.
  4. The load event exposes the complete string, including data:image/png;base64,. Assigning it directly to preview.src displays the image.

Get only the raw Base64 payload

Most HTML needs the complete data URL. Remove the prefix only when another API explicitly asks for raw Base64:

const dataUrl = reader.result;
const comma = dataUrl.indexOf(',');
const base64Only = comma === -1 ? '' : dataUrl.slice(comma + 1);

MDN documents the equivalent pattern of removing data:*/*;base64, through the comma. Do not encode reader.result again: it is already a data URL and a second Base64 pass produces the wrong bytes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

A reusable Promise helper

For application code, wrapping the reader in a Promise makes it easy to await the conversion:

function pngFileToDataUrl(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => resolve(reader.result));
    reader.addEventListener('error', () => reject(reader.error));
    reader.readAsDataURL(file);
  });
}

input.addEventListener('change', async () => {
  const file = input.files[0];
  if (!file) return;

  try {
    preview.src = await pngFileToDataUrl(file);
  } catch (error) {
    console.error(error);
  }
});

Why not just use btoa()?

btoa() and atob() operate on binary strings. They are useful when you already have bytes represented as a suitable binary string, but btoa() is not a general Unicode encoder: characters outside its byte range can throw an exception. A PNG is binary data, and a File is asynchronous, so readAsDataURL() avoids converting the file through an unsafe text representation.

If you deliberately use lower-level byte handling, first obtain bytes from an ArrayBuffer and convert those bytes to a binary string or use a byte-aware Base64 implementation. Do not pass arbitrary human-readable Unicode text to btoa() and assume the result represents a PNG.

Debug a broken Base64 PNG

When an image is missing or appears as a broken-image icon, inspect the value assigned to src and check these failure modes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

The prefix is wrong

For a PNG, the beginning must be exactly data:image/png;base64,. A misspelled media type, an omitted ;base64 marker, or malformed media parameters can be ignored or rejected without a useful console message.

The comma is missing

The comma terminates the metadata. Keep it between the prefix and the encoded bytes.

The value was encoded twice

A string returned by readAsDataURL() already contains both the prefix and Base64 payload. Put it directly in src, or remove only the prefix when raw Base64 is required. Never call btoa() on the complete data URL.

The payload was truncated or altered

Copy the entire encoded string. Truncation, accidental edits, or inserted whitespace can corrupt the decoded PNG. Store the value in a variable or generate it at runtime rather than manually retyping a long literal.

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.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

The selected object is empty

Check input.files[0] before reading. A cancel action, a reset input, or a failed file selection leaves it empty.

The file is not actually a PNG

The accept attribute does not validate file contents. If correctness matters, inspect the file on the server or decode it before accepting it. A renamed non-PNG file can still be selected by a user.

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

Inline Base64 versus a normal image URL

Use a data URL when the document should be self-contained: small prototypes, single-file demos, generated HTML, or an artifact that must travel as one document. Use a normal URL when the image is reused, updated independently, or large enough that keeping it outside the HTML improves delivery and caching.

Consideration Base64 data URL Normal src URL
Deployment One document contains markup and image bytes. HTML and the image are separate assets.
Caching The embedded bytes are tied to that document. The image can be cached and reused independently.
Updates Changing the image requires changing the document. Replace the asset without rewriting every HTML document.
Readability Source contains a long opaque string. Source remains a short, recognizable path or URL.
Size The HTML becomes larger because it carries encoded bytes. The binary remains a separate response.
Origin and security Modern browsers treat data URLs as unique opaque origins; top-level navigation to data: is blocked in modern browsers. The resource follows the normal origin and request rules of its URL.

There is no universal browser byte limit for data URLs that you can safely assume across implementations. If a document approaches a browser’s practical limits, switch to a normal asset URL and verify behavior in the browsers you support.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Inspect and test the result

  1. Open developer tools and inspect the image element.
  2. Confirm that src starts with data:image/png;base64,.
  3. Use the console to check preview.complete and preview.naturalWidth. A decoded image normally has a positive natural width.
  4. If the value came from a server, verify that the response contains the PNG bytes you expect before encoding them.
  5. Keep alt text meaningful even when the image is only decorative; use an empty alt="" when it truly conveys no information.

Or skip the browser setup

If what you need first is a clean website screenshot to place into an HTML document, ScreenshotNeo returns a screenshot with one GET request. Before capture it accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed, while bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. The response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server also lets Claude, Cursor, or another MCP client call take_screenshot, get_page_info, and capture_pdf.

See the ScreenshotNeo API documentation for request options. The following examples use the supplied API endpoint and save the returned asset locally.

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 has a free plan with 1,000 screenshots each month and no card required. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. After you receive an image, convert that local file with the browser workflow above or your normal server-side Base64 encoder, then place the resulting data URL in src.

Create a free ScreenshotNeo account to start with 1,000 screenshots per month and no card.

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

Frequently Asked Questions

Can I use a Base64 PNG in an email?

A self-contained data URL can be useful for single-file artifacts such as some HTML email workflows, but email clients apply their own filtering and size policies. Test the exact clients and message pipeline you support.

Should I store the Base64 string in my database?

Only do so when the application specifically benefits from a self-contained representation. For reusable or frequently updated images, storing the binary as an asset and serving a normal URL keeps HTML and records smaller and independently cacheable.

How do I turn the data URL back into a PNG file?

Split at the first comma, decode the part after it as Base64, and write the resulting bytes to a file with a .png extension. Preserve the image/png declaration so your code can reject an unexpected media type.

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
PC Slower Than It Used to Be?Free scan - under a minute
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.