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

In a browser, a data URL is already a URL for image bytes. Create an HTMLImageElement, assign the complete data URL to src, and wait for its load or error event.

function imageFromDataUrl(dataUrl) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error("Could not load image data URL"));
    img.src = dataUrl;
  });
}

const img = await imageFromDataUrl(dataUrl);
document.querySelector("#preview").append(img);
console.log(img.naturalWidth, img.naturalHeight);

This is browser-side code. It does not validate arbitrary input or set an application-specific size limit, so production code should apply the checks and limits described below.

What a data URL contains

The usual syntax is data:[<media-type>][;base64],<data>. A PNG commonly begins with data:image/png;base64,; JPEG and WebP use their corresponding media types. The comma separates metadata from the payload.

The media type matters

If the media type is omitted, the data URL defaults to text/plain;charset=US-ASCII, not an image. The URL syntax can therefore be valid while the image decoder still rejects the contents.

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.

Base64 is optional

;base64 tells the browser that the payload is Base64-encoded. Without it, the data portion can use percent-encoded characters instead. Do not add or remove the marker unless the payload encoding matches it.

Load an image from an existing data URL

new Image() and document.createElement("img") create the same kind of element. Keep the entire string, including data:, the media metadata, the comma, and the payload.

async function showDataUrl(dataUrl, selector) {
  const img = await imageFromDataUrl(dataUrl);
  document.querySelector(selector).replaceChildren(img);
  return img;
}

showDataUrl("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB...", "#preview")
  .then(img => {
    console.log(`Loaded ${img.naturalWidth}×${img.naturalHeight}`);
  })
  .catch(error => {
    console.error(error);
  });

Set the event handlers before assigning src. Loading and decoding are asynchronous; setting src does not mean that pixels are ready immediately. Use naturalWidth and naturalHeight after load when intrinsic dimensions are needed.

Validate the value before loading it

A user-facing application should reject malformed or unexpectedly large input before inserting it into the document. This lightweight check verifies the basic structure and an allow-list of image types; it does not prove that the bytes are a valid, decodable image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function validateImageDataUrl(value) {
  if (typeof value !== "string" || !value.startsWith("data:")) {
    throw new TypeError("Expected a data URL");
  }

  const comma = value.indexOf(",");
  if (comma < 0) {
    throw new TypeError("Data URL has no payload separator");
  }

  const metadata = value.slice(5, comma).toLowerCase();
  const allowedTypes = ["image/png", "image/jpeg", "image/webp", "image/gif"];
  const mediaType = metadata.split(";")[0] || "text/plain;charset=us-ascii";

  if (!allowedTypes.includes(mediaType)) {
    throw new TypeError(`Unsupported media type: ${mediaType}`);
  }

  const isBase64 = metadata.split(";").includes("base64");
  const payload = value.slice(comma + 1);
  if (isBase64 && !/^[A-Za-z0-9+/]*={0,2}$/.test(payload)) {
    throw new TypeError("Payload is not valid Base64 syntax");
  }

  return { mediaType, isBase64, payload };
}

The final authority is the decoder: a syntactically correct URL can still contain bytes that are not a supported image. Apply your own maximum string length or decoded-byte limit when input can come from users or remote systems.

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.

Use an object URL when the input is a Blob

A Blob is binary data, not a data-URL string. Convert it to an opaque browser URL with URL.createObjectURL(), assign that URL to an image, and revoke it after the image is no longer accessible.

function imageFromBlob(blob) {
  const objectUrl = URL.createObjectURL(blob);
  const img = new Image();

  return new Promise((resolve, reject) => {
    img.onload = () => {
      // Keep objectUrl alive while the image is still displayed or downloadable.
      resolve({ img, objectUrl });
    };
    img.onerror = () => {
      URL.revokeObjectURL(objectUrl);
      reject(new Error("Could not decode Blob as an image"));
    };
    img.src = objectUrl;
  });
}

async function removeImage({ img, objectUrl }) {
  img.remove();
  URL.revokeObjectURL(objectUrl);
}

Do not revoke the object URL immediately after load if the user still needs to view, open, or save the image. Revoke it when the element and any related interaction are finished.

Choose the representation your application already has

Input Recommended path Lifecycle
Complete data URL string Assign the original string to img.src No object URL is created or revoked; still handle load and error
Binary image in a Blob Call URL.createObjectURL(blob), then assign the returned URL Revoke only after the image is no longer accessible

There is no universal performance winner established here. The practical choice is based on whether you already hold text-encoded data or binary data, plus the memory and lifetime requirements of your interface.

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

Display, draw, or inspect the result

Once the promise resolves, the image has decoded successfully and can be appended, styled, or used in APIs that require a loaded image. For example:

const img = await imageFromDataUrl(dataUrl);
img.alt = "Uploaded preview";
img.width = Math.min(img.naturalWidth, 800);
document.querySelector("#preview").replaceChildren(img);

Keep the original data URL when you need to serialize the image back into application state. If you only need a temporary preview, prefer a Blob and object URL so the encoded string does not have to remain in state.

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.

Why a valid data URL can fail

Malformed prefix or separator

Check that the value starts with data: and contains a comma. Do not strip the prefix or metadata before assigning src.

Wrong media type

The declared type must match the bytes, such as image/png for PNG data. A missing type defaults to plain text.

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

Incorrect Base64 flag

If ;base64 is present, the payload must actually be Base64. If the payload is percent-encoded text, remove the marker rather than decoding and re-encoding blindly.

Invalid image bytes

The data-URL grammar does not turn arbitrary text into an image. Confirm that the payload came from a real, supported image encoder and that it was not truncated during transport.

Reading dimensions too early

Wait for load before using naturalWidth, naturalHeight, canvas drawing, or other dimension-dependent work.

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

Content Security Policy blocks the source

The page’s CSP img-src directive controls permitted image sources. If the same value works elsewhere but fails on the deployed page, inspect the actual response policy and allow only the schemes and sources your security design requires.

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

Input is too large

Browser documentation reports practical maximum data-URL sizes of 512 MB in Chromium and Firefox and 2,048 MB in Safari/WebKit, while noting that browsers are not required to support a particular limit. Treat these as implementation ceilings, not sensible application targets. Large images should normally remain as Blobs or files instead of being kept as enormous embedded strings.

Security and browser support

Data URLs and the Image() constructor are widely available across modern browsers, with established support documented since July 2015. Data URLs are treated as unique opaque origins. They have also had security issues in top-level navigation, and modern browsers block top-level navigation to them; displaying an image through img is a different use case. Never treat arbitrary untrusted data as a general-purpose navigation target.

Validate source and size before processing untrusted values, use a restrictive CSP, and avoid retaining large Base64 strings longer than necessary. Browser limits and policies can change, so verify compatibility for the browsers your application officially supports.

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 clean image of a web page rather than decoding an image string, ScreenshotNeo provides a website screenshot API and MCP server. A single request returns PNG, JPEG, WebP, or PDF output. For example, using the API documented at https://screenshotneo.com/docs/:

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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

It accepts cookie or 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, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, 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 for Claude, Cursor, and other MCP clients.

The same endpoint can be called from Python or Node.js:

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}`);

Every plan includes the full feature set: full-page and selector captures, lazy-image loading, dark mode, device presets, arbitrary viewports, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture for 100 URLs per call, usage reporting, an OpenAPI specification, and familiar parameter names for easier migration. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can I use a data URL directly in CSS?

Yes. CSS properties such as background-image accept URL values, including data URLs, subject to the page’s Content Security Policy. Use an image element instead when you need load events or intrinsic dimensions.

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

Does assigning src change or recompress the image?

No. Assigning the URL asks the browser to decode the embedded bytes; it does not by itself rewrite the data URL or encode the image again.

Why is this not a Node.js solution?

Standard Node.js does not provide browser DOM globals such as HTMLImageElement or Image. Use browser code for this method, or choose a server-side image library when processing images without a browser.

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.