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.
#1 Best Overall
- 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
- 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. - The
changeevent runs after a selection. If the user cancels,input.files[0]is absent and the handler returns. readAsDataURL(file)reads the binary file asynchronously.- The
loadevent exposes the complete string, includingdata:image/png;base64,. Assigning it directly topreview.srcdisplays 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.
Rank #2
- 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:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #3
- 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.
Rank #4
- 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.
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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Best Value
- 【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
- Open developer tools and inspect the image element.
- Confirm that
srcstarts withdata:image/png;base64,. - Use the console to check
preview.completeandpreview.naturalWidth. A decoded image normally has a positive natural width. - If the value came from a server, verify that the response contains the PNG bytes you expect before encoding them.
- Keep
alttext meaningful even when the image is only decorative; use an emptyalt=""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.
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.
Quick Recap
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.




