Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
Canvas

How to Save an HTML Image as a JPEG (Canvas, Local Files, and Web Pages)

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

Use the method that matches what you actually have. If the pixels are already in an HTML <canvas>, call canvas.toBlob(callback, "image/jpeg", quality), create a temporary object URL, and download the resulting Blob. If you only have an <img> element or a file downloaded from a page, first load those pixels into a canvas (or use an image editor/converter), then export the canvas as JPEG. Renaming .png to .jpg does not convert the encoded data.

First identify which kind of “HTML image” you have

The phrase can describe three different starting points. The correct workflow depends on the source, not on the filename shown in a browser tab.

Starting point Use this approach Important limitation
Pixels already drawn in a canvas Export directly with toBlob("image/jpeg"). The canvas must not be tainted by an image loaded without permitted CORS access.
An ordinary <img> element Draw the image into a canvas, then export the canvas. A cross-origin image can make export fail with SecurityError.
A downloaded PNG, WebP, or other file Open it in a conversion-capable application or use a local browser canvas page. Changing the extension alone leaves the original encoding unchanged.

The browser API documented by MDN and the WHATWG HTML Standard handles the canvas case. Exact right-click menus and editor dialogs vary by browser, operating system, and application, so this guide uses a repeatable code path instead of assuming a particular menu.

Export a canvas as JPEG with toBlob()

HTMLCanvasElement.toBlob() encodes the canvas asynchronously. Pass "image/jpeg" as the requested MIME type and a quality value from 0 to 1. A value such as 0.92 is a preference for the encoder, not a promise of a particular file size or visual result.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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
canvas.toBlob((blob) => {
  if (!blob) {
    throw new Error("The browser could not create an image Blob.");
  }

  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "image.jpg";
  document.body.appendChild(link);
  link.click();
  link.remove();

  // Give the browser a moment to start the download before releasing the URL.
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}, "image/jpeg", 0.92);

The callback receives a Blob, whose type should be checked before you rely on the extension:

canvas.toBlob((blob) => {
  if (!blob) return;
  console.log(blob.type, blob.size); // expected type: image/jpeg
}, "image/jpeg", 0.92);

If the requested type is unsupported or omitted, the documented fallback is PNG. Do not label a fallback Blob .jpg merely because the download name says so.

A complete page-author example

This example assumes the page already has a canvas and a button. It paints a background so transparent canvas pixels do not become an unintended color when encoded as JPEG.

<canvas id="art" width="1200" height="800"></canvas>
<button id="save" type="button">Save JPEG</button>

<script>
const canvas = document.querySelector("#art");
const ctx = canvas.getContext("2d");

// JPEG has no alpha channel; choose the background you want to keep.
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#202124";
ctx.font = "48px sans-serif";
ctx.fillText("Canvas export", 80, 140);

 document.querySelector("#save").addEventListener("click", () => {
  canvas.toBlob((blob) => {
    if (!blob || blob.type !== "image/jpeg") {
      alert("JPEG export was not available.");
      return;
    }
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "canvas-export.jpg";
    document.body.appendChild(link);
    link.click();
    link.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  }, "image/jpeg", 0.92);
});
</script>

The object URL keeps the encoded Blob available to the download link without copying the entire image into a JavaScript string. Revoke it after the browser has had time to use it; revoking synchronously can interrupt some downloads.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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

Convert an ordinary <img> element

An image displayed by HTML is not automatically a canvas. Draw it into a canvas first, then export that canvas. The image must have loaded before drawImage() runs.

const image = document.querySelector("#source");
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);

canvas.toBlob((blob) => {
  if (!blob) return;
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "converted.jpg";
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}, "image/jpeg", 0.9);

For an image on another origin, set image.crossOrigin = "anonymous" before assigning its src, and the image server must send an appropriate CORS response header. The client cannot override a server that does not grant access. Without suitable CORS access, the canvas becomes tainted and toBlob() or toDataURL() can throw SecurityError.

Convert a local file in a browser-only page

This self-contained page lets a user choose a local image, draws it at its native dimensions, and downloads a JPEG. Because the file is selected locally, it avoids the cross-origin fetch issue that affects remote images.

<input id="file" type="file" accept="image/*">
<label>JPEG quality
  <input id="quality" type="number" min="0" max="1" step="0.01" value="0.92">
</label>
<button id="convert" type="button" disabled>Convert</button>

<script>
const fileInput = document.querySelector("#file");
const qualityInput = document.querySelector("#quality");
const convertButton = document.querySelector("#convert");
let selectedFile = null;

fileInput.addEventListener("change", () => {
  selectedFile = fileInput.files[0] || null;
  convertButton.disabled = !selectedFile;
});

convertButton.addEventListener("click", () => {
  if (!selectedFile) return;
  const image = new Image();
  const sourceUrl = URL.createObjectURL(selectedFile);
  image.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = image.naturalWidth;
    canvas.height = image.naturalHeight;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(image, 0, 0);
    URL.revokeObjectURL(sourceUrl);

    const quality = Math.min(1, Math.max(0, Number(qualityInput.value)));
    canvas.toBlob((blob) => {
      if (!blob) return;
      const downloadUrl = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = "converted.jpg";
      link.click();
      setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
    }, "image/jpeg", quality);
  };
  image.onerror = () => {
    URL.revokeObjectURL(sourceUrl);
    alert("The selected file could not be decoded as an image.");
  };
  image.src = sourceUrl;
});
</script>

The canvas dimensions in this example use the source image’s intrinsic dimensions. If you need a smaller JPEG, set the canvas width and height to the desired output dimensions and draw the source into that rectangle before exporting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

When toDataURL() is appropriate

canvas.toDataURL("image/jpeg", quality) returns a data URL immediately, which is convenient for a small preview or a short-lived hyperlink:

const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
const link = document.createElement("a");
link.href = dataUrl;
link.download = "preview.jpg";
link.click();

For large images, MDN recommends the Blob/object-URL route instead. A data URL stores the whole encoded image in one in-memory string, increasing peak memory use. Whichever API you choose, inspect the returned prefix or Blob type if the exact format matters.

JPEG-specific trade-offs

  • Lossy encoding: JPEG trades some image information for smaller output. Text, sharp UI edges, and repeated editing can show ringing or blur.
  • No transparency: JPEG has no alpha channel. Paint a deliberate background before drawing transparent artwork.
  • Quality is not a size target: the 0–1 quality argument controls encoder preference; it does not guarantee a maximum number of bytes.
  • PNG fallback: an unsupported request can produce PNG. Verify the actual MIME type rather than trusting a filename.

Troubleshooting common failures

The downloaded file is PNG

Check blob.type or the beginning of the data URL. The browser may not support the requested encoder, or the request may have been unsupported. Use PNG deliberately, or choose a conversion tool that provides JPEG encoding.

SecurityError appears during export

One or more pixels came from another origin without the required CORS permission. Configure the image host to allow the requesting origin, set crossOrigin before src, and reload the image. A canvas that has already been tainted cannot be “untainted” by JavaScript; reload it after fixing the response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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 callback receives null

Encoding failed or the browser could not create the requested Blob. Handle the null case, check the canvas dimensions, and try a supported output type such as PNG to separate a canvas problem from a JPEG-encoder problem.

The download is blank or the old image appears

Wait for the source image’s load event before drawing. Also ensure the canvas is not zero-sized and that you revoke the object URL only after the download has started.

The result is unexpectedly large

Reduce the canvas dimensions for the intended display size, then adjust quality gradually. Do not assume a particular quality value produces a predictable byte count; image content and browser encoder behavior affect the result.

The result looks different from the source

JPEG is lossy, and transparent source pixels require a chosen background. Compare at the final display size, and keep the original lossless file if you may need to edit or re-export later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and reliability checklist

  • Prefer toBlob() for large canvases to avoid one giant data URL string.
  • Export asynchronously and keep the interface responsive while encoding.
  • Use intrinsic dimensions when preserving resolution matters; resize before export when bandwidth or storage matters more.
  • Check the resulting MIME type and Blob for every export path.
  • Release object URLs after the browser has consumed them to avoid retaining image data.
  • Handle decode, CORS, null-Blob, and download failures explicitly instead of treating a clicked link as proof that conversion succeeded.

Or skip the browser setup

If your real goal is a JPEG of a web page rather than extraction of one embedded image, ScreenshotNeo can render the URL and return an image through one request. It is a website screenshot API and MCP server; it does not bypass CORS to extract a protected source file. Before capture, it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and each response reports the page verdict and billing status in headers.

Use the API documentation at https://screenshotneo.com/docs/ for the full option set. A JPEG request can be made with cURL:

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -d format=jpeg 
  -o shot.jpg

The same endpoint can be called from Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com", "format": "jpeg"},
    timeout=90,
)
r.raise_for_status()
open("shot.jpg", "wb").write(r.content)

And from Node.js:

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com',
  format: 'jpeg'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.jpg', bytes));

ScreenshotNeo also offers an MCP server for AI agents such as Claude and Cursor, plus controls for full-page captures, device and retina settings, CSS selectors, custom JavaScript, waits, request blocking, headers, cookies, geolocation, PDF output, caching, signed links, asynchronous jobs, bulk capture, and usage reporting. Every plan includes every feature. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to get started.

Frequently Asked Questions

Can I export a canvas at a different size than it is displayed?

Yes. Set the canvas’s pixel width and height to the target output dimensions, then draw the source into that rectangle before calling the export method. CSS display size and canvas pixel dimensions are separate.

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

Should I keep the original file after making a JPEG?

Yes when future editing, transparency, or repeated exports matter. JPEG encoding is lossy, so retaining the original gives you a better source for later conversions.

Why does a remote image work visually but fail when exported?

Displaying an image does not grant script access to its pixels. The image server must explicitly permit the relevant CORS request; otherwise drawing it taints the canvas and blocks export.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.