HTML markup is not an image file, so you cannot convert the <img> tag itself. Convert the pixels it displays: draw the loaded image onto a canvas and export it as image/jpeg. For large images, use toBlob(); for batch or server-side work, use ImageMagick. If the image comes from another site, that site must allow your page to read its pixels through CORS.
What “convert an HTML image” means
An HTML image is usually an <img> element that points to an image file, or a graphic drawn into a <canvas>. HTML is markup, not bitmap data. To make a JPEG, first get the rendered pixels, then encode those pixels in JPEG format.
The browser approach works for an image your page can load and draw. It gives you a downloadable JPEG without uploading the image to a conversion service. If your task is to convert local files repeatedly, a command-line tool is usually easier to automate.
Convert an <img> to JPEG in the browser
Basic example: load, draw, and download
This complete example waits for the image to load, uses its intrinsic dimensions rather than its displayed CSS size, draws it onto a canvas, and downloads the JPEG:
#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.
<img id="source" src="photo.png" alt="">
<button id="save">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 image has not loaded successfully.');
}
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext('2d');
if (!context) throw new Error('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 0.9 argument requests JPEG quality on a scale from 0 to 1. JPEG is lossy: a lower value generally means a smaller file and less visual fidelity. Choose a value based on the image and how it will be used; there is no single setting that is best for every image.
naturalWidth and naturalHeight refer to the source image’s intrinsic dimensions. If you instead set the canvas dimensions to the element’s CSS width and height, you will create an output at those displayed dimensions, which can reduce detail. A canvas must have nonzero dimensions, and drawing should happen only after the image has loaded.
Use toBlob() for larger images
toDataURL() encodes the entire image as a string in memory. For larger images, the browser’s toBlob() method avoids that large data URL string. MDN recommends the Blob approach for this reason. Create an object URL for the download and revoke it after the browser has had a chance to use it:
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();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}, 'image/jpeg', 0.9);
The callback is asynchronous, so handle the Blob inside it. Verify both that a Blob exists and that its type is image/jpeg before treating the result as a JPEG.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →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.
Check the actual output format
The browser API accepts a requested MIME type, but format support is not universal. Browsers must support PNG; JPEG is widely supported, but an unsupported requested format is exported as PNG instead. The WHATWG HTML Standard describes this fallback. That is why the example checks the data: URL prefix or Blob type rather than trusting the filename: naming a PNG download .jpg does not make its contents JPEG.
Cross-origin images: the CORS requirement
If the src points to another origin, the browser may display the image but still refuse to export its pixels. The canvas must remain origin-clean. When a cross-origin image is drawn without the necessary permission, calling toDataURL() or toBlob() can throw a SecurityError.
For a cross-origin image to be readable by canvas, both sides of the request matter: set the image’s crossOrigin property before assigning src, and the image server must send an appropriate CORS response allowing your origin. Then draw the image only after it loads:
const image = new Image();
image.crossOrigin = 'anonymous';
image.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
// Export the canvas here.
};
image.onerror = () => {
console.error('The image failed to load or the server did not permit access.');
};
image.src = 'https://images.example/image.png';
Replace the example URL with the image URL. Setting crossOrigin on your side does not grant permission by itself: the image server has to allow the request. If it does not, client-side JavaScript cannot use the canvas API to export those pixels. Use an image you control, ask the server to enable CORS, or run a conversion in an environment that has legitimate access to the source file.
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.
Convert a local image with ImageMagick
For a local file, automation, or server-side processing, ImageMagick converts formats from the command line. Install ImageMagick for your operating system, then run the command from the directory containing the input file:
magick input.png output.jpg
ImageMagick uses the output extension to select the format. To request a JPEG quality setting, add -quality before the output filename:
magick input.png -quality 85 output.jpg
ImageMagick documents JPEG quality scaling, sampling controls, and an 8-bit default output depth. Its quality number belongs to ImageMagick’s encoder and should not be treated as directly equivalent to the browser canvas quality number. If you need finer control over sampling, colorspace, or file size, ImageMagick exposes those controls; use its JPEG documentation to choose settings for your workflow.
Which conversion method fits?
| Need | Browser canvas | ImageMagick |
|---|---|---|
| Where it runs | In the page’s browser | Locally or on a server that can read the file |
| Input access | Loaded image; cross-origin pixels require server CORS permission | File accessible to the command-line process |
| Output handling | Data URL for a quick download, or Blob for larger output | Writes the named output file |
| Control | Requested MIME type and quality value | Quality and additional JPEG-related controls |
| Best fit | One-off or interactive conversion in a web page | Repeatable batch or server-side conversion |
Or skip the browser setup
If what you need is a screenshot of a webpage that displays an image—not conversion of an arbitrary image file—ScreenshotNeo can capture a rendered page as an image or PDF. It is a different job from drawing an existing image into your own canvas. ScreenshotNeo supports JPEG output; check the API documentation for the documented output-format parameters before relying on a particular format in an integration.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsRank #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
Here is the one-call cURL example for a webpage capture:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The call shown saves the response to shot.webp; the filename alone does not select the response format. Consult the docs for the JPEG option if the output must be JPEG. ScreenshotNeo removes cookie or consent banners, newsletter popups, and chat widgets before capture, and each of those cleanup steps can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with X-Page-Verdict and X-Billed response headers indicating the result. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. See ScreenshotNeo for the service details, or sign up free.
Troubleshooting
The download is PNG even though the filename ends in .jpg
Check the MIME prefix or Blob’s type. The browser may have fallen back to PNG because the requested encoder was unsupported. Do not rename the extension and assume the file has converted; use a browser that supports JPEG encoding or convert the image with ImageMagick.
Canvas export throws SecurityError
A drawn cross-origin image made the canvas non-origin-clean. Configure the image with crossOrigin before setting src, and have the source server return CORS permission for your origin. If you cannot change the server and it does not permit access, the browser cannot export the pixels through canvas.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows 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 reinstallThe canvas is blank or the image appears missing
Confirm that the image loaded successfully before drawing it. Check image.complete and that image.naturalWidth is greater than zero; attach an onerror handler to catch failed loads. Also confirm that the canvas has nonzero width and height and that the code draws the same image element you checked.
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.
The output is unexpectedly small or blurry
Set canvas dimensions from the image’s intrinsic dimensions if you want to preserve its source pixel dimensions. Lower JPEG quality can reduce file size at the expense of fidelity; raising it may preserve more detail but can produce a larger output. For additional JPEG encoding controls, use ImageMagick rather than expecting canvas’s single quality argument to expose them.
The command says magick was not found, or no output appears
Install ImageMagick and make sure its command-line executable is available in your shell’s path. Check that the input file exists in the current directory, or provide its full path. If the command completes but the file is not where expected, inspect the output path and directory permissions.
Practical notes on quality, performance, and repeatability
- Keep the original. JPEG is lossy, so repeated JPEG-to-JPEG conversions can compound quality loss. If you may need another export, retain the source image and convert from it.
- Use the right in-browser output form. A data URL is convenient for small, immediate downloads. A Blob avoids building a large encoded string and is the better fit for large images.
- Make dimensions explicit. The canvas output dimensions determine the pixel dimensions available to the encoder; CSS sizing of the original element is not necessarily the source resolution.
- Plan batch work around file access. ImageMagick is suited to repeatable command-line work on files the process can read. Browser conversion depends on the page being allowed to load and export the image.
- Check content, not labels. Confirm the produced MIME type or inspect the output using a suitable image viewer or file utility before depending on a converted file in another system.
Frequently Asked Questions
Can changing an image URL from .png to .jpg convert it?
No. A filename or URL extension is a label; conversion requires encoding the image pixels in JPEG format. Use canvas export or an image converter.
Free tools Windows power users keep installed
One-click scans. No signup required.
Can I use this browser method for an image inside an SVG or CSS background?
It depends on whether you can load or render the graphic into an image or canvas that your page is allowed to read. The canvas export restrictions still apply, including CORS for cross-origin content.
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.

