October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Canvas

How to Convert an HTML Image to JPEG in the Browser or with ImageMagick

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

HTML is markup, not a bitmap. To convert an image displayed by an <img> element, draw its pixels onto a canvas and encode that canvas as image/jpeg. Use toBlob() for large files, or toDataURL() when a quick download is sufficient. For local files and batch jobs, ImageMagick converts directly from the command line.

What “HTML image” can mean

The conversion method depends on what you actually have:

  • An <img> element: the browser has decoded an image file and is rendering it. Canvas can copy those rendered pixels and encode them as JPEG.
  • A canvas already containing artwork: skip drawImage() and export that canvas directly.
  • An image URL in HTML: the browser must load the URL first. If it is on another origin, the image server must grant CORS access before canvas can export it.
  • A complete web page: that is a screenshot task rather than a file-format conversion. A page-capture service can render the page and return a JPEG screenshot.

The examples below convert the pixels the browser has rendered; they do not rewrite HTML markup or preserve the original file’s metadata.

Convert an <img> element to JPEG in a browser

Complete download example with toDataURL()

This self-contained page waits for the image, sizes the canvas to the image’s intrinsic dimensions, draws it, requests JPEG at quality 0.9, verifies that JPEG was actually produced, and starts a download.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Wacom Intuos Small, Wired Graphic Drawing Tablet with Pen + Software
  • Wacom Intuos Small Graphics Drawing Tablet: Enjoy industry leading tablet performance in superior control and precision with Wacom's EMR, battery free technology that feels like pen on paper
  • Works With All Software: Wacom Intuos tablet can be used in any software program to explore new facets of digital creativity; draw, paint, edit photos/videos, create designs, and mark up documents
  • What the Professionals Use: Wacom's industry leading pen technology and pen to paper feeling makes it the preferred drawing tablet of professional graphic designers
  • Software and Training Included: Only Wacom gives you software with every purchase. Register your Intuos tablet and gain access to some of the best creative software and Wacom's online training
  • Wacom is the Global Leader in Drawing Tablet and Displays: For over 40 years in pen display and tablet market, you can trust that Wacom to help you bring your vision, ideas and creativity to life
<!doctype html>
<html lang='en'>
<meta charset='utf-8'>
<title>Convert an image to JPEG</title>
<img id='source' src='photo.png' alt=''>
<button id='save' type='button'>Save JPEG</button>
<script>
const image = document.querySelector('#source');
const button = document.querySelector('#save');

button.addEventListener('click', () => {
  if (!image.complete || image.naturalWidth === 0) {
    throw new Error('The source image has not loaded or has no usable pixels.');
  }

  const canvas = document.createElement('canvas');
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;

  const context = canvas.getContext('2d');
  if (!context) {
    throw new Error('This browser could not create a 2D canvas context.');
  }

  context.drawImage(image, 0, 0);

  const jpegDataUrl = canvas.toDataURL('image/jpeg', 0.9);
  if (!jpegDataUrl.startsWith('data:image/jpeg')) {
    throw new Error('JPEG encoding was not supported; the browser returned another format.');
  }

  const link = document.createElement('a');
  link.href = jpegDataUrl;
  link.download = 'converted.jpg';
  link.click();
});
</script>

The first argument to toDataURL() is the requested MIME type. The quality argument is a number from 0 to 1; lower values generally produce smaller files with more visible compression. A browser must support PNG, and it may not support every requested format. When JPEG is unsupported, the canvas API falls back to PNG, which is why checking the returned data: prefix matters.

Wait for an image that loads asynchronously

If the source URL is assigned by JavaScript, attach the conversion to the image’s load event rather than assuming it is ready:

const image = new Image();
image.src = 'photo.png';
image.addEventListener('load', () => {
  const canvas = document.createElement('canvas');
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  canvas.getContext('2d').drawImage(image, 0, 0);

  canvas.toBlob((blob) => {
    if (!blob || blob.type !== 'image/jpeg') {
      throw new Error('JPEG Blob was not produced.');
    }
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'converted.jpg';
    link.click();
    URL.revokeObjectURL(url);
  }, 'image/jpeg', 0.9);
});
image.addEventListener('error', () => {
  console.error('The source image could not be loaded.');
});

Prefer toBlob() for large images

toDataURL() places the entire encoded image in a JavaScript string. That is convenient for a small, immediate download, but it creates a large in-memory value. toBlob() encodes to a binary Blob instead; create a temporary object URL, download it, and release the URL when finished.

canvas.toBlob((blob) => {
  if (!blob || blob.type !== 'image/jpeg') {
    throw new Error('JPEG Blob was not produced');
  }

  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'converted.jpg';
  link.click();
  URL.revokeObjectURL(url);
}, 'image/jpeg', 0.9);

Some applications need to upload the result rather than download it. Pass the same Blob to fetch(), XMLHttpRequest, or FormData instead of creating an anchor.

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

Control dimensions, quality, and transparency

Use the source’s intrinsic size unless you intentionally want a resize

naturalWidth and naturalHeight preserve the decoded image dimensions. Setting a different canvas width or height scales the image during drawImage(); it does not improve detail that was not present in the source. For a deliberate resize, choose the target dimensions first, then draw into that canvas.

Rank #2
Sale
XPPen Deco 01 V3 10x6 Drawing Tablet, 16K Battery-Free Stylus, 8 Keys
  • Word-first 16K Pressure Levels: The upgraded stylus features 16,384 levels of pressure sensitivity and supports up to 60 degrees of tilt, delivering smoother lines and shading for a natural drawing experience. With no battery or charging needed, it operates like a real pen, making it easy for beginners to create effortlessly. This functionality helps novice artists develop their skills and explore their creativity without the intimidation of complex tools
  • Designed for Beginners: This drawing pad desinged with 8 customizable shortcuts for both right and left-hand users, express keys create a highly ergonomic and convenient work platform
  • Perfectly Adapted for Android: The XPPen Deco 01 V3 art tablet supports connections with Android devices running version 10.0 and above. It is recommended to download the XPPen Tools Android application, which adapts to your smartphone's screen aspect ratio, ensuring accurate mapping. It also supports mapping on Android screens with different aspect ratios in portrait mode
  • Large Drawing Space, Bigger Bold Inspiration: This expansive drawing pad has10 x 6.25-inch helps you break through the limit between shortcut keys and drawing area
  • Easy Connectivity for Beginners: The Deco 01 V3 offers USB-C to USB-C connectivity, plus adapters for USB C. This ensures easy connection to various devices, allowing beginner artists to set up quickly and focus on their creativity without compatibility concerns. Whether using a laptop, tablet, or desktop, the Deco 01 V3 provides a seamless experience, making it an ideal choice for those just starting their digital art journey

Choose JPEG quality for the job

Quality is not a percentage of original pixels. It is an encoder hint from 0 through 1. Start around 0.8 to 0.9 for photographs, inspect the result, and lower it only when file size matters more than fine detail. Text, diagrams, screenshots, and sharp UI edges can show ringing or block artifacts at lower quality; PNG may be a better format for those images.

JPEG cannot carry transparency

If the source has transparent areas, decide what background those pixels should have before drawing the image. Fill the canvas first, then draw the source:

const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext('2d');
context.fillStyle = '#ffffff';
context.fillRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0);

Export that canvas with toBlob() or toDataURL(). Otherwise, transparent regions may not have the background you expect when represented in a format without an alpha channel.

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

Handle cross-origin images correctly

A canvas containing pixels from another origin must remain origin-clean. If the image server has not granted access with CORS, exporting the canvas raises a SecurityError. JavaScript cannot bypass that restriction.

Set crossOrigin before assigning src, and configure the image server to return an appropriate Access-Control-Allow-Origin response header:

Rank #3
Tablet, 11 Inch Android 16 Tablets with Keyboard Gemini AI 3.5, 24GB+128GB
  • 【Android 16 Tablet with Gemini AI 3.5】The 11 inch TABWEE T90 brings a cleaner, smarter tablet experience for work, study and home use. Android 16 adds a simpler lock screen, customizable Quick Settings, improved video calls with background blur and portrait light, easier cloud photo selection and enhanced Linux terminal support. With Gemini AI 3.5, you can search, translate, summarize notes, organize ideas and plan tasks more efficiently—ideal for online classes, reading, video calls and light office work
  • 【11 Inch FHD IPS Display for Streaming, Reading and Learning】Enjoy a bigger and clearer viewing experience on the 11 inch FHD display with 1920 x 1200 resolution and an 84.9% screen-to-body ratio. The fully laminated TDDI screen delivers more natural colors, smoother touch response, and a more immersive feel when watching movies, reading documents, viewing recipes, or studying online. With Widevine L1 support, dual smart speakers, and 380-nit brightness, this Android tablet is ideal for Netflix-style streaming, YouTube, music, eBooks, online lessons, and comfortable indoor entertainment
  • 【24GB RAM + 128GB ROM, More Space for Daily Needs】Android 16 tablet comes with up to 24GB RAM, including 8GB built-in RAM and 16GB virtual memory expansion, helping daily apps run smoothly for browsing, video watching, note-taking, email, and study apps. The 128GB ROM provides plenty of room for photos, documents, music, videos, learning materials, and work files. Need more storage? The TF card slot supports up to 2TB expansion, so you can keep more movies, books, files, and family memories without constantly deleting content. Memory expansion path: Settings > System > Memory Expansion
  • 【T615 Octa-Core + 8000mAh Battery for Long Days】Powered by the Unisoc T615 octa-core processor, T90 delivers reliable everyday speed for streaming, video calls, online lessons, reading, emails and document editing. The 8000mAh battery supports up to 11H video playback, 8H daily entertainment or 40H music, while smart power management helps reduce background drain, making it ready for flights, commutes, study sessions and busy workdays
  • 【13MP Camera with Google Lens】The 13MP rear camera works with Google Lens to make daily tasks easier. Scan documents, translate text, identify objects, search products, capture handwritten notes, or save useful information in seconds. The 5MP front camera is suitable for video calls and clear face-to-face communication. With dual-band 5G WiFi, Bluetooth 5.0, and support for GPS, GLONASS, Galileo, and Beidou, this Android tablet offers fast downloads, stable wireless connections, easy accessory pairing, and reliable location support for travel, maps, and mobile use
const image = new Image();
image.crossOrigin = 'anonymous';
image.addEventListener('load', () => {
  const canvas = document.createElement('canvas');
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  canvas.getContext('2d').drawImage(image, 0, 0);

  canvas.toBlob((blob) => {
    if (!blob || blob.type !== 'image/jpeg') {
      throw new Error('The browser did not produce a JPEG.');
    }
    // Upload or download blob here.
  }, 'image/jpeg', 0.9);
});
image.src = 'https://images.example.com/photo.png';

If you control neither the page nor the image host, use a server-side conversion process or obtain the file through an authorized backend. Loading an image in an <img> tag can succeed while canvas export still fails; the CORS response must be present when the image is fetched.

Export an existing canvas directly

When the image was drawn by a chart, editor, game, or other canvas-based application, there is no need to create a second canvas:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = document.querySelector('#drawing');
canvas.toBlob((blob) => {
  if (!blob || blob.type !== 'image/jpeg') {
    throw new Error('JPEG export failed.');
  }
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'drawing.jpg';
  link.click();
  URL.revokeObjectURL(url);
}, 'image/jpeg', 0.9);

The same origin-clean rule applies to every image drawn into that canvas, including images added by third-party libraries.

Convert files with ImageMagick

For local files, repeatable builds, or batch processing, ImageMagick provides a direct command-line path. Its magick command selects the output format from the destination extension:

magick input.png output.jpg

Set JPEG quality with the -quality option:

magick input.png -quality 85 output.jpg

ImageMagick documents JPEG quality scaling, sampling controls, and an 8-bit default output depth. This route does not depend on browser CORS rules and is easier to place in a script or server worker. Verify the result with your normal image inspection tools, especially when converting screenshots or text-heavy graphics where JPEG artifacts are more noticeable.

Rank #4
Wacom Intuos Medium, Bluetooth Graphic Drawing Tablet with Pen + Software
  • Wacom Intuos Medium Bluetooth Graphics Drawing Tablet: Enjoy industry leading tablet performance in superior control and precision with Wacom's EMR battery free technology that feels like pen on paper
  • Works With All Software: Wacom Intuos tablet can be used in any software program to explore new facets of digital creativity; draw, paint, edit photos/videos, create designs, and mark up documents
  • Wireless Superior Connectivity: Connect wirelessly via Bluetooth or directly using USB-A cable which enables you to work, draw or create whether it's at a desk, on the sofa, in classrom or even outside
  • Software and Training Included: Only Wacom gives you software with every purchase. Register your Intuos tablet and gain access to some of the best creative software and Wacom's online training
  • Wacom is the Global Leader in Drawing Tablet and Displays: For over 40 years in pen display and tablet market, you can trust that Wacom to help you bring your vision, ideas and creativity to life

Which method should you use?

Method Best for Input access Output and control
ScreenshotNeo Rendering a complete URL when you want a clean page screenshot; it removes consent banners, popups, and chat widgets before capture, bills only clean shots, and has the lowest paid plan in this comparison. Public or authenticated pages supported by its request options PNG, JPEG, WebP, or PDF; automation, waiting, device, headers, cookies, and other capture controls
Browser canvas One interactive image already displayed in your page Same-origin or CORS-enabled pixels JPEG quality from 0 to 1; use a data URL or Blob
ImageMagick Local files, backend jobs, and batches Files the process can read Command-line quality and additional JPEG controls

Choose canvas when the user is already looking at the image and the conversion should happen locally. Choose ImageMagick when the source is a file or the process must run unattended. Choose a page screenshot API when the requirement is to capture the rendered page rather than extract one source image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo captures a URL through a website screenshot API and can return PNG, JPEG, WebP, or PDF. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. You can turn each cleanup step off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Use the endpoint as documented at https://screenshotneo.com/docs/. Replace the example URL with the page you need to render:

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

The service also supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets and arbitrary viewports, retina scale, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector or network-idle waits, ad and tracker blocking, custom headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration.

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is included on every plan. Create a free ScreenshotNeo account to try the 1,000 monthly screenshots without adding a card.

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.

Troubleshooting

The result begins with data:image/png

The browser did not support the requested JPEG encoding and followed the specified PNG fallback. Check the MIME prefix from toDataURL() or the type property from toBlob() before naming or uploading the file as JPEG. Use a browser with JPEG canvas encoding or keep the PNG result.

Best Value
Sale
Wacom Intuos Pro Medium, Bluetooth Graphic Drawing Tablet with ProPen 3
  • WACOM’S BEST PEN TECHNOLOGY: Pro Pen 3 offers amazing precision, 8192 pressure levels, tilt support & lag-free tracking for smooth, precise strokes; choose slim, straight or flared grip, adjust balance & button layout for precision and comfort
  • DIAL INTO PRODUCTIVITY: Speed up and stay in the creative flow with 10 customizable tablet ExpressKeys & 2 mechanical dials conveniently located at the top of the tablet and close to your keyboard for efficiency
  • DESIGNED FOR MODERN MONITORS: With a versatile 16:9 format perfect for multiple monitors and wide displays; medium size has a large active area with a small footprint 11.4 x 8.1” / 291 x 206 mm
  • SLEEK AND STURDY: Measuring 4mm at its thinnest this professional-grade drawing tablet feels like pen-on-paper on your desk, combined with the robust durability of magnesium making it equally suited for your office or life on the go
  • WIRELESS FREEDOM: use Intuos Pro with USB or connect wirelessly via Bluetooth to multiple computers with a simple switch

The browser throws SecurityError

The canvas is not origin-clean. Confirm that the image host sends CORS permission, set image.crossOrigin before src, and wait for a fresh load. If the server cannot be changed, perform the conversion where the process can legally read the image.

The canvas is blank or has zero dimensions

Inspect image.complete, naturalWidth, and naturalHeight. A failed request, an image that has not finished loading, or a broken URL leaves no usable pixels. Run conversion from the load handler and report the error event to the user.

The JPEG is unexpectedly blurry or large

Adjust quality in small steps and inspect the actual file. Higher quality normally increases size; lower quality can damage text and sharp edges. If the source is a diagram or interface screenshot, compare PNG before accepting JPEG artifacts.

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

The download does not start

Call the anchor click in response to the button event, assign a filename ending in .jpg, and for Blob exports keep the object URL alive until the click has been issued. For application uploads, send the Blob directly instead of relying on a browser download.

magick is not found

ImageMagick is not available on the current machine or its executable is not on the process path. Install it through your operating system’s approved package process, then verify that the magick command is callable before running a conversion job.

Performance and reliability notes

  • Use toBlob() for large images to avoid a full encoded copy in a JavaScript string.
  • Do not start conversion until the image has loaded; asynchronous loading is the normal case for network URLs.
  • For many files, move conversion to ImageMagick or a server worker instead of keeping many canvases and encoded results in one browser tab.
  • Check the actual MIME type before storing a result. A filename alone does not prove that the bytes are JPEG.
  • When capturing a complete page, account for consent handling, bot checks, failed loads, and dynamic content. ScreenshotNeo reports page verdict and billing headers so an application can distinguish a clean billed capture from a failed or non-billable response.

Frequently Asked Questions

Can an animated image become an animated JPEG?

No. JPEG is a still-image format. A canvas export represents the pixels from the frame that was drawn at conversion time; preserving animation requires a format and workflow designed for multiple frames.

Does converting to JPEG preserve the original file’s metadata?

The canvas and ImageMagick workflows described here create a new encoded file. Do not assume that camera, editing, or application metadata from the source will be retained; inspect the output if metadata matters.

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

Can I convert an image that is only referenced by a remote URL?

Yes, if the browser can load it and the remote server permits canvas access with CORS. Otherwise, use an authorized server-side process or a page-capture workflow instead of trying to bypass the origin restriction.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.