HTML is text and cannot be Base64-encoded as a JPG until it has been rendered into pixels. For a webpage or element, use a browser such as Puppeteer and request a JPEG screenshot with encoding: 'base64'. If your application already draws the content on a canvas, use canvas.toDataURL('image/jpeg', quality) instead. The first method captures browser layout; the second serializes an existing bitmap.
Choose the conversion route
“Convert HTML to a Base64 JPG” can describe two different inputs. Select the route that matches the state of your content:
| Route | Input | Result | Use it when |
|---|---|---|---|
| Puppeteer screenshot | A rendered page or selected element | Screenshot bytes or a raw Base64 string | You need the browser’s layout, CSS, fonts, images and page state |
| Canvas serialization | Pixels already present in an HTML canvas | A JPEG data URL, optionally reduced to raw Base64 | Your application has already drawn the desired bitmap |
Neither method encodes markup itself. A string such as <h1>Invoice</h1> must first be rasterized if the desired result is an image of how it looks in a browser.
Capture rendered HTML with Puppeteer
Puppeteer’s screenshot API can return a Base64 string directly. Set the image type to JPEG, choose a quality value from 0 to 100 supported by your installed Puppeteer version, and set encoding to 'base64'.
#1 Best Overall
- 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.
Minimal page screenshot
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle0' });
const base64 = await page.screenshot({
type: 'jpeg',
quality: 85,
encoding: 'base64'
});
console.log(base64); // bare Base64 JPEG payload
} finally {
await browser.close();
}
})();
The value printed by this example contains the encoded JPEG bytes, not a data: prefix. Add the prefix only when the receiving API or HTML attribute expects a complete data URL:
const dataUrl = `data:image/jpeg;base64,${base64}`;
Capture the full document
For a page-length image, add fullPage: true. The viewport still affects responsive layout, so set it explicitly when reproducible output matters.
await page.setViewportSize?.({ width: 1440, height: 900 });
const base64 = await page.screenshot({
fullPage: true,
type: 'jpeg',
quality: 85,
encoding: 'base64'
});
The setViewportSize line above is illustrative of viewport control in browser automation; use the viewport method exposed by your installed Puppeteer release (for current Puppeteer, that is typically page.setViewport({ width: 1440, height: 900 })).
Capture one element
When only a card, report, or invoice is needed, locate the element and use its element screenshot method. This avoids cropping unrelated page content.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →const element = await page.$('#invoice');
if (!element) throw new Error('Invoice element was not found');
const base64 = await element.screenshot({
type: 'jpeg',
quality: 90,
encoding: 'base64'
});
Wait for the element’s content and visual assets before capturing. A screenshot taken while fonts, images, lazy content, or client-side data are still loading can differ from the intended result.
Rank #2
- 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.
Save the Base64 result
To write a normal JPG file, decode the string rather than writing the Base64 characters as if they were binary:
const fs = require('node:fs');
fs.writeFileSync('page.jpg', Buffer.from(base64, 'base64'));
Conversely, to embed it in HTML, keep the data URL form:
document.querySelector('#preview').src = `data:image/jpeg;base64,${base64}`;
Convert canvas pixels with toDataURL
If the desired image is already drawn into a canvas, no page screenshot is necessary. The canvas API returns a data URL containing a media type, the text base64, and the encoded payload.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesconst dataUrl = canvas.toDataURL('image/jpeg', 0.85);
const comma = dataUrl.indexOf(',');
if (comma === -1) throw new Error('Unexpected canvas data URL');
const base64 = dataUrl.slice(comma + 1);
The second argument is JPEG quality from 0 to 1; 0.85 is an example, not a universal optimum. Keep dataUrl when the destination accepts a complete data URL. Extract the substring after the comma only when it explicitly requires raw Base64.
Canvas limitations
- It does not render arbitrary HTML. Text and CSS outside the canvas are not included.
- JPEG support varies by browser. The WebKit reference notes that PNG is the required baseline format, while JPEG availability and behavior can differ. Test the browsers that matter to your application.
- Origin restrictions can taint the canvas. If you draw cross-origin images without appropriate CORS permission, reading pixels may fail with a security exception. Host assets with suitable CORS headers or avoid drawing inaccessible images.
- Large canvases consume memory. A data URL duplicates image data in a string, so prefer a Blob workflow for very large output when your interface permits it.
Data URL versus raw Base64
These representations are related but not interchangeable:
Rank #3
- 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.
data:image/jpeg;base64,/9j/...is a complete data URL. It carries the MIME type and can be assigned directly to an image’ssrc./9j/...is the Base64 payload alone. It is suitable for an API field that separately specifies JPEG, but it is not itself a browser image URL.
Check the receiving system’s contract before removing or adding the prefix. Sending the wrong form is a common cause of “invalid image” errors.
Make captures deterministic
Rendered output depends on browser state. For repeatable files:
Free tools Windows power users keep installed
One-click scans. No signup required.
- Set a fixed viewport and device scale factor when your Puppeteer version exposes those settings.
- Navigate with an appropriate readiness condition, then wait for application-specific selectors or data.
- Wait for web fonts and images that affect layout; network idle alone may not mean lazy content is visible.
- Choose
fullPage, an element screenshot, or a clip according to the required dimensions. - Set JPEG quality deliberately. Higher quality generally produces larger files; lower quality introduces more compression artifacts around text and sharp edges.
- Use PNG instead when lossless text, transparency, or exact pixel fidelity is more important than JPEG output. A JPEG has no alpha channel.
Or skip the browser setup
ScreenshotNeo provides a GET-based website screenshot API when you want rendered output without maintaining a browser process. It removes cookie and consent banners, newsletter popups and chat widgets before capture; bot checks, blank pages, failed loads and timeouts are not billed, and responses identify the page verdict and billing status in 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 API returns PNG, JPEG or WebP. Request JPEG and then Base64-encode the response bytes in your application:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
For JPEG output, add the service’s JPEG format parameter alongside the other query parameters. See the ScreenshotNeo API documentation for the current parameter names and all 63 capture options, including full-page and element capture, device presets, retina scale, custom CSS and JavaScript, waits, request blocking, headers, cookies, geolocation, caching, signed links, asynchronous jobs and bulk capture.
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)
After receiving the bytes, encode them with your language’s Base64 library and prepend data:image/jpeg;base64, only if a data URL is required.
Rank #4
- 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
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(`Screenshot failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
const base64 = bytes.toString('base64');
const dataUrl = `data:image/jpeg;base64,${base64}`;
ScreenshotNeo’s Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting
The output is a Base64 string but not a JPG
Verify that the screenshot option explicitly sets type: 'jpeg', or that canvas serialization requests image/jpeg. Base64 is only an encoding; it does not determine the underlying image format.
The image appears blank or incomplete
Capture after the relevant selector exists and after asynchronous content, fonts and images have loaded. For lazy-loaded pages, scroll or trigger the application’s loading mechanism before taking a full-page screenshot.
The receiver rejects the value
Determine whether it expects raw Base64 or a data URL. Add data:image/jpeg;base64, for the latter and remove everything through the first comma for the former.
Canvas throws a security exception
A cross-origin image likely tainted the canvas. Serve the image with compatible CORS headers and set the image’s CORS mode before loading it, or use same-origin assets.
Best Value
- 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.
JPEG looks soft or text is damaged
Increase quality, capture at a larger pixel size, or use PNG when lossless edges and transparency matter. JPEG quality values are a trade-off, not a guarantee of a particular file size.
Puppeteer details differ after an upgrade
Screenshot options are version-sensitive. The options reference reviewed for this article showed Puppeteer 25.12.0 on September 29, 2026; check the documentation matching your installed version before relying on a method or option name.
Performance, reliability and cost considerations
Browser screenshots incur startup, navigation and rendering work. Reuse a browser process for batches, close pages you no longer need, and avoid capturing more pixels than required. Element screenshots are usually a better fit than full-page images when downstream systems only need one component. Base64 increases payload size compared with binary bytes, so decode promptly or use binary transport where possible.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Canvas serialization is fast for an existing bitmap but can create large in-memory strings. For repeated exports, compare quality, dimensions and transfer size with the limits of your API or database. A hosted service shifts browser maintenance to the provider; ScreenshotNeo also supports caching with a chosen TTL, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, and a usage API for operational tracking.
Which method should you use?
- Choose Puppeteer when the source is a live HTML document and you need browser layout, CSS, responsive behavior or a selected element.
- Choose canvas.toDataURL when the pixels already exist in a canvas and you need a browser-side export.
- Choose a hosted capture API when you want an HTTP workflow or AI-agent integration instead of running browser infrastructure.
Frequently Asked Questions
Can I Base64-encode HTML directly as a JPG?
No. HTML must first be rendered or rasterized into pixels. Use a browser screenshot for page markup or canvas serialization for an existing bitmap.
Should I send the data URL or only the Base64 text?
Follow the receiving system’s format. A data URL includes the `data:image/jpeg;base64,` prefix; raw Base64 is only the text after the comma.
Does JPEG preserve transparency?
No. JPEG has no alpha channel. Use PNG when transparent backgrounds are required.
What quality value should I choose?
For Puppeteer, use the 0–100 range supported by your installed version; for canvas, use 0–1. Select the highest compression level that still preserves the detail your output needs.
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.

