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

Embed a PNG in HTML by placing its 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 declares the encoding, and the comma separates that metadata from the encoded bytes. You can create this value in a browser with FileReader.readAsDataURL(), generate it during a build, or write it directly into a single-file HTML document.

Use the correct PNG data URL format

A PNG data URL follows the grammar data:[media-type][;base64],data. For a PNG, the complete prefix is exactly data:image/png;base64,. The comma is required; everything after it is the Base64 representation of the PNG’s binary bytes.

<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB...' alt='A one-pixel PNG'>

Replace the shortened payload above with the complete encoded file. Base64 is case-sensitive, so do not change its letters, numbers, plus signs, slashes, or trailing equals signs. Keep meaningful alternative text in alt so the image remains understandable to people using assistive technology.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Convert a PNG selected in the browser

For a file chosen by a visitor, the native browser workflow is FileReader.readAsDataURL(). When reading finishes, reader.result is already a complete data URL, including the data:image/png;base64, prefix.

<!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.readAsDataURL(file);
    });
  </script>
</body>
</html>

Why this code works

  1. accept='image/png' filters the file picker toward PNG files. It is a usability hint, not a substitute for validating the file.
  2. input.files[0] retrieves the first selected File. The guard handles cancellation or an empty selection.
  3. readAsDataURL(file) reads the binary file asynchronously and prepares a data URL.
  4. The load handler assigns that complete URL to img.src, so the browser decodes and displays it.

Show the generated value or copy it

If another part of your application needs the string, use reader.result inside the load handler. This example displays it in a text area and provides a copy button:

<textarea id='dataUrl' rows='8' cols='80' readonly></textarea>
<button id='copy' type='button'>Copy data URL</button>
<script>
  const output = document.querySelector('#dataUrl');
  const copy = document.querySelector('#copy');

  reader.addEventListener('load', () => {
    output.value = reader.result;
    preview.src = reader.result;
  });

  copy.addEventListener('click', async () => {
    await navigator.clipboard.writeText(output.value);
  });
</script>

In a real page, define reader in the same scope as the event handlers. The important point is that the value is already a complete URL; do not Base64-encode it a second time.

Extract only the raw Base64 payload when an API requires it

Some APIs want only the encoded bytes and not the declaration prefix. Remove everything through the first comma:

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 #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
const dataUrl = reader.result;
const comma = dataUrl.indexOf(',');
const rawBase64 = comma === -1 ? '' : dataUrl.slice(comma + 1);

For a known PNG, a stricter version also checks the prefix before extracting:

const prefix = 'data:image/png;base64,';
if (!dataUrl.startsWith(prefix)) {
  throw new Error('The selected file did not produce a PNG data URL');
}
const rawBase64 = dataUrl.slice(prefix.length);

Use the full data URL for an HTML src attribute. Use rawBase64 only when the receiving API explicitly asks for the payload without data:*/*;base64,.

Embed a known Base64 value in static HTML

For a self-contained document, paste the complete data URL directly into the image element:

<figure>
  <img src='data:image/png;base64,PASTE_THE_COMPLETE_VALUE_HERE' alt='Company logo' width='240' height='80'>
  <figcaption>Company logo</figcaption>
</figure>

Keep the payload intact when templating or minifying. Accidental truncation, inserted whitespace, or line-wrapping can make the image undecodable. If a build system stores the value in a variable, concatenate the prefix and payload without adding spaces:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
<script>
  const pngBase64 = 'ENCODED_PNG_BYTES';
  const image = document.createElement('img');
  image.alt = 'Generated chart';
  image.src = 'data:image/png;base64,' + pngBase64;
  document.body.append(image);
</script>

Generate the data URL outside the browser

Build scripts are useful when the PNG is part of a single-file artifact, email template, prototype, or generated report. Read the file as bytes, Base64-encode those bytes, and prepend the PNG prefix.

Python

import base64
from pathlib import Path

png_bytes = Path('image.png').read_bytes()
data_url = 'data:image/png;base64,' + base64.b64encode(png_bytes).decode('ascii')
print(data_url)

Node.js

import { readFile } from 'node:fs/promises';

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

Both examples preserve the binary bytes and produce a browser-ready URL. If you are writing an HTML file, escape the value according to the templating system you use, then place it in the quoted src attribute.

Data URL versus a normal PNG URL

Concern Base64 data URL Normal image URL
Document size Binary data is copied into the HTML, increasing the document. The HTML stays smaller because the image is separate.
Caching The image is tied to the containing document rather than fetched as an independent asset. The image can be cached and reused as its own resource.
Updates Changing the image requires changing the document that contains it. The image can be replaced independently at its URL.
Deployment One HTML file contains everything needed for the image. You must deploy and serve the HTML and image resource.
Readability The long encoded payload is difficult to inspect or edit. The short path is easier to recognize in source.
Origin and security behavior Modern browsers treat data: URLs as unique opaque origins, and top-level navigation to them is blocked in modern browsers. The image is fetched from its normal document or asset origin.

Choose a data URL for a small, self-contained asset when portability matters more than document size. Keep a normal URL when caching, independent updates, source readability, or a smaller HTML response is more important. Exact practical size limits vary by browser and should be checked against the documentation for the browsers you support.

Understand btoa() and atob()

btoa() encodes a binary string and atob() decodes one. They are not general arbitrary-Unicode encoders: characters outside the byte range can cause an error, and Unicode text must first be converted to bytes. A PNG is already binary, so FileReader.readAsDataURL() is the safer browser-native path for a File or Blob.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Do not run btoa() on the complete result of readAsDataURL(). That result is already Base64 plus its data-URL prefix. Encoding it again produces a different string that cannot be used as the original image.

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

Troubleshoot a broken PNG

The image icon appears, but the PNG does not display

  • Check that the value starts with exactly data:image/png;base64,.
  • Confirm the comma is present between the prefix and payload.
  • Make sure the payload was not truncated, wrapped, or altered by a template.
  • Verify that you assigned the complete reader.result, not an object or an empty variable.

The browser reports an invalid or ignored data URL

A misspelled base64 marker or malformed media parameters may be ignored without a useful error. Use the canonical lowercase prefix and remove unexpected characters before the comma. If you extracted a payload for an API, remember that the HTML image still needs the prefix added back.

The selected file is not a PNG

The accept attribute influences the picker but does not guarantee the file’s contents. Check the file type and, where correctness matters, validate the PNG signature or process the file through an image library before embedding it.

The image works in a preview but not after saving the page

Inspect the generated HTML and compare the saved src value with the value assigned in the browser. Common causes are a templating escape, a missing comma, a shortened string, or whitespace inserted into the payload. Preserve the entire encoded value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

The HTML became unexpectedly large

That is inherent to inline encoding: the binary is now part of the document. Use a normal PNG URL or an asset pipeline when the image is large, reused across pages, or updated independently.

Performance, accessibility, and security considerations

  • Performance: Inline data makes the containing document larger and prevents the image from being managed as an independent cached asset. Keep inline PNGs small and limited to assets that benefit from being self-contained.
  • Accessibility: Provide useful alt text. If the image is purely decorative, use an empty alt value rather than exposing meaningless encoded content to assistive technology.
  • Integrity: Treat the Base64 string as binary data. Do not normalize characters, insert spaces, or trim meaningful trailing equals signs.
  • Navigation: A data URL is intended for embedding; modern browsers block top-level navigation to data: URLs for security reasons.
  • Maintenance: Keep the source PNG and a reproducible conversion step in your project so you can regenerate the embedded value when the artwork changes.

Or skip the browser setup

If your real task is obtaining a clean PNG of a web page before embedding it, ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request returns a screenshot or PDF, while its capture process accepts consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

Here is the one-call cURL form (see the ScreenshotNeo documentation for options):

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 provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Its plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 shots. After receiving an image, you can store it as a normal PNG or WebP asset and embed it with the same data-URL method described above. Create a free ScreenshotNeo account to get started.

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

Frequently Asked Questions

What does the comma in a PNG data URL do?

It separates the media-type and encoding declaration from the Base64 payload. Omitting it makes the browser parse the value incorrectly.

Should I remove the data-URL prefix before putting the value in an HTML image?

No. An HTML src needs the complete data:image/png;base64, prefix. Remove that prefix only when a separate API explicitly requests raw Base64.

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.