The correct way to save an HTML image as a JPEG depends on what you have. If the pixels are already in an HTML <canvas>, call canvas.toBlob() with the MIME type image/jpeg, then download the returned Blob. If you only see an ordinary <img> on a page, obtain its source file or draw it into a canvas first. Renaming .png to .jpg does not convert the encoding.
This guide covers the browser APIs, a complete working example, cross-origin failures, quality and memory choices, and a way to capture a rendered web page without setting up a browser locally.
Choose the right route first
| What you start with | Recommended route | What you receive |
|---|---|---|
| Pixels already drawn in a canvas | canvas.toBlob(callback, "image/jpeg", quality) |
A JPEG Blob that can be downloaded or uploaded |
| A canvas data URL is needed for a small operation | canvas.toDataURL("image/jpeg", quality) |
A string beginning with data:image/jpeg, when supported |
| An ordinary image element | Load the image, draw it into a canvas, then export | A new encoded file; cross-origin rules still apply |
| A file downloaded from a web page | Open it in a conversion-capable application or use a page-authored canvas flow | A converted file only after it is actually re-encoded |
The browser APIs establish the canvas routes. Exact menu names for a particular browser, operating system, or image editor vary, so do not rely on a universal right-click instruction.
Save canvas pixels as a JPEG
toBlob() is the normal choice for a real image export. It asks the browser to encode the canvas and passes a Blob to your callback. The second argument is the requested MIME type and the optional quality value is between 0 and 1. A value such as 0.92 is an encoding preference, not a promised file size or identical visual result across browsers.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute#1 Best Overall
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
Complete runnable example
Save this as canvas-jpeg.html, open it in a browser, and press the button. The demo draws pixels locally, so it does not encounter cross-origin restrictions.
<!doctype html>
<meta charset="utf-8">
<title>Canvas to JPEG</title>
<canvas id="canvas" width="900" height="500"></canvas>
<label>
JPEG quality
<input id="quality" type="number" min="0" max="1" step="0.01" value="0.92">
</label>
<button id="save" type="button">Save JPEG</button>
<script>
const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
// Example pixels. Replace this drawing with your own canvas rendering.
const gradient = context.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, "#2457d6");
gradient.addColorStop(1, "#e84b8a");
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "white";
context.font = "bold 44px sans-serif";
context.fillText("Canvas export", 48, 90);
document.querySelector("#save").addEventListener("click", () => {
const quality = Number(document.querySelector("#quality").value);
canvas.toBlob((blob) => {
if (!blob) {
console.error("The browser did not produce an image Blob.");
return;
}
// Check the encoded format instead of trusting the filename.
if (blob.type !== "image/jpeg") {
console.error("Requested JPEG, received:", blob.type);
return;
}
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = objectUrl;
link.download = "canvas-image.jpg";
document.body.appendChild(link);
link.click();
link.remove();
// Keep the URL alive through the download initiation, then release it.
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}, "image/jpeg", quality);
});
</script>
The callback can receive null, so the example checks it. It also checks blob.type; if the browser cannot provide the requested format, PNG is the documented fallback. A .jpg filename alone is not proof that the bytes are JPEG.
Why use an object URL?
URL.createObjectURL(blob) gives the download link a temporary URL without turning the entire encoded image into one JavaScript string. Release that URL with URL.revokeObjectURL() after the browser has had time to start the download. For large images, this Blob/object-URL approach avoids the large in-memory string created by toDataURL().
Use toDataURL when a data URL is genuinely useful
For a small image or an API that specifically requires a data URL, use:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallRank #2
- High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
- Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
- Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
- Sleek, durable metal casing
- Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
const jpegDataUrl = canvas.toDataURL("image/jpeg", 0.92);
const link = document.createElement("a");
link.href = jpegDataUrl;
link.download = "image.jpg";
link.click();
The returned string should start with data:image/jpeg when JPEG encoding was honored. Inspect the prefix before assigning a JPEG extension. Because the complete encoded image is held in a string, prefer toBlob() for large canvases or repeated exports.
Convert an ordinary HTML image element
An <img> element is only a display object; it does not automatically expose a JPEG version. Load its pixels into a canvas, then export that canvas:
async function imageElementToJpeg(image, quality = 0.92) {
if (!image.complete || image.naturalWidth === 0) {
await new Promise((resolve, reject) => {
image.addEventListener("load", resolve, { once: true });
image.addEventListener("error", () => reject(new Error("Image failed to load")), { once: true });
});
}
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => {
if (!blob) return reject(new Error("No Blob was produced"));
if (blob.type !== "image/jpeg") return reject(new Error(`Received ${blob.type}, not JPEG`));
resolve(blob);
}, "image/jpeg", quality);
});
}
const image = document.querySelector("#source");
imageElementToJpeg(image).then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "converted.jpg";
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
This works directly when the image is same-origin or the remote server grants the required CORS access. Setting an image’s crossOrigin property does not grant permission by itself; the image host must send an appropriate CORS response before the pixels can be exported.
Set CORS before assigning the source
const image = new Image();
image.crossOrigin = "anonymous";
image.src = "https://images.example.test/photo.png";
image.onload = () => {
// Draw and export only after the CORS-enabled load succeeds.
};
If the server does not permit the request, use a server-side conversion route or obtain a permitted copy of the file. A client-side script cannot waive the browser’s origin restriction.
Rank #3
- What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
- Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
- Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
- Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
- Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
What happens when you export as JPEG?
Quality is a range, not a size target
The quality argument is a number from 0 to 1 for lossy formats such as JPEG. It controls the encoder’s preference; it does not promise a particular number of kilobytes. Image dimensions, content, browser implementation, and the selected quality all affect the result. Choose a value for the visual use case, then inspect the resulting Blob’s size and appearance.
PNG fallback is possible
If the requested type is unsupported or invalid, canvas export uses PNG. Always inspect blob.type or the data-URL prefix before storing a file with a JPEG extension. If you need a JPEG specifically, treat any other MIME type as a failed conversion and handle it rather than silently renaming it.
JPEG is lossy
Converting a canvas to JPEG applies lossy encoding. Fine details can change, especially as quality is reduced. The browser API does not provide a promise of lossless output or a fixed visual threshold.
Common failures and fixes
“The downloaded file is PNG”
- Check
blob.typebefore downloading. - Confirm the requested string is exactly
image/jpeg. - If the browser falls back to PNG, retain the PNG extension or use a conversion environment that supports JPEG.
SecurityError during toBlob() or toDataURL()
- Find every image, video frame, or other resource drawn into the canvas.
- For foreign origins, configure the resource server to allow the requesting origin and set
crossOriginbeforesrc. - If you cannot change that server, do not attempt to bypass the restriction in client-side JavaScript; fetch or convert the asset through an authorized server-side workflow.
The callback receives null
The encoding did not produce a Blob. Check that the canvas has a valid width and height, that the document is not exhausting memory, and that your callback handles failure instead of creating a download link.
Rank #4
- GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
- BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
- EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
- TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
- WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.
The image is unexpectedly large
- Use
toBlob()rather than keeping a data URL string. - Reduce the canvas dimensions before export when the destination does not need full resolution.
- Lower the quality value gradually and inspect the actual file; no quality value guarantees a particular size.
The download has the wrong extension
Browsers may use the filename you provide even when the bytes have another format. Verify the MIME type, choose .jpg only for image/jpeg, and use a matching extension for a PNG fallback.
The page image is a protected or blocked resource
A displayed image may require cookies, authorization, or anti-bot handling. In that situation, the browser page may show pixels that your standalone script cannot fetch. Use an authorized session or a capture service that supports the required request context; do not try to defeat access controls.
Performance and reliability considerations
- Use the natural image dimensions when reproducing the source pixels, but set an intentional canvas size when you need a smaller output.
- Do not revoke an object URL before the browser has begun using it; delayed revocation, as in the example, avoids interrupting the download.
- For repeated exports, release each object URL and discard unused canvases so memory can be reclaimed.
- Test the actual output MIME type, dimensions, and byte size in the same browser environment used by your users.
- Keep the original file if you may need lossless pixels later; JPEG export is a new, lossy encoding.
Or skip the browser setup
If your real goal is to save a rendered web page rather than convert a local image, ScreenshotNeo provides a website screenshot API and MCP server. It accepts a URL and returns a clean PNG, JPEG, WebP, or PDF. A single request is enough:
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}`);
See the ScreenshotNeo documentation for request options and response details. Before capture, it accepts the cookie or consent banner as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.
The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; Growth is $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing provides two months free, and every feature is included on every plan. This captures a webpage rendering; it does not replace the original image file or bypass authorization.
Best Value
- 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
- 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
- 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
- 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
- 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.
Create a free ScreenshotNeo account to try the 1,000 monthly screenshots without a card.
When each method is appropriate
- Choose
toBlob()when your application already owns the canvas pixels and needs a downloadable or uploadable JPEG. - Choose
toDataURL()only when a compact, string-based workflow outweighs its memory cost. - Draw an
<img>into a canvas when you need to re-encode an ordinary image and can satisfy CORS. - Use a conversion-capable editor or authorized server workflow for a downloaded file, protected resource, or cross-origin image that cannot be exported in the browser.
- Use ScreenshotNeo when the deliverable is a clean screenshot of a URL and you want the browser automation, consent cleanup, and billing checks handled for you.
Frequently Asked Questions
Can I preserve the original PNG quality by saving it as JPEG?
No. JPEG export is lossy. Keep the original PNG if you may need its exact pixels later.
Does a JPEG quality of 0.92 guarantee the same file size in every browser?
No. It is an encoder preference in the 0–1 range; dimensions, image content, and browser implementation determine the resulting bytes.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Can ScreenshotNeo convert a file stored only on my computer?
The supplied API description is for capturing a URL. A local file must first be made available through an authorized, reachable URL or converted locally.
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.

