← Homework · · 09 MIN
Convert Images to WebP in the Browser with JavaScript
How my free image converter turns JPEG and PNG into WebP without uploading anything: canvas, toBlob, quality, transparency and memory cleanup.
You don't need a server to convert an image to WebP. Every modern browser can decode an image, draw it onto a canvas and encode it again in another format, all on the user's own device. That is how the free image converter on this site works: you drop in JPEG, PNG or WebP files, pick a format and a quality, and nothing is ever uploaded.
This article walks through the code behind it. The core trick fits in a few lines, and most tutorials stop there. The parts that make it a usable tool take more thought: converting a batch without freezing the page, transparent images turning black, freeing memory, and checking that the browser gave you the format you asked for.
Why convert in the browser at all
Most online converters upload your file to a server, convert it there and send it back. That works, but it has costs:
- Privacy. Screenshots, scans and personal photos leave your device. With a browser-only tool, the file never goes anywhere.
- Speed. No upload or download. For a batch of large photos, that is most of the waiting time.
- Running cost. There is no server doing the work, so a free tool stays free to run.
The trade-off is that you are limited to what the browser's built-in encoder supports, with its default settings. For a quick, private conversion, that is usually enough.
The core: image, canvas, blob
The whole conversion is three steps: decode the file into an image, draw it on a canvas, and ask the canvas to encode itself.
Step 1: load the file as an image
function loadImage(url: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error("could not decode image"));
img.src = url;
});
}
const srcUrl = URL.createObjectURL(file);
const img = await loadImage(srcUrl);
URL.createObjectURL gives the File from the file input or drag and drop a temporary URL that only exists in this tab. The <img> element decodes it using the browser's own decoders, which means the input can be anything the browser can display.
Step 2: draw it on a canvas at full size
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("no canvas context");
ctx.drawImage(img, 0, 0);
Use naturalWidth and naturalHeight, not width and height. The natural size is the image's real pixel size; the other two can be affected by CSS or attributes, and you would silently resize the output.
Step 3: encode it with toBlob
const blob: Blob = await new Promise((resolve, reject) => {
canvas.toBlob(
(b) => (b ? resolve(b) : reject(new Error("encoding failed"))),
"image/webp",
0.82, // quality, from 0 to 1
);
});
toBlob is the important call. The second argument is the output format, and the third is the quality for lossy formats. Prefer it over toDataURL: toDataURL returns a base64 string about a third larger than the binary data, and building that string for a big photo is slow and memory-hungry. A Blob can go straight into a download link.
Choosing the quality setting
My converter defaults to a quality of 0.82, a middle ground between file size and visible artifacts for photos. There is nothing magic about the number, so the tool exposes a slider.
Two things to know about quality:
- It only applies to lossy formats, JPEG and WebP. PNG is lossless, so the browser ignores the value; in the tool the slider is disabled when PNG is selected.
- Re-encoding never adds detail back. Converting a JPEG to WebP decodes the JPEG, artifacts included, and compresses that again. Start from the best original you have.
The tool shows the before and after size for every file, along with the percentage saved. Converting a PNG screenshot to WebP often makes it far smaller; converting an already small JPEG can sometimes make it bigger. Showing the number lets people decide for themselves.
Transparency: the black background bug
PNG and WebP support transparency. JPEG does not. If you draw a transparent PNG onto a canvas and export it as JPEG, the transparent pixels come out black, which is almost never what anyone wants.
The fix is to paint a background before drawing the image, only when the target format has no alpha channel:
if (format === "image/jpeg") {
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(img, 0, 0);
White is the safe default for logos and screenshots. If you build a more advanced tool, a background colour picker is an easy addition.
Check what the browser actually gave you
This is the step most tutorials skip. If a browser cannot encode the format you ask for, toBlob does not throw an error. The HTML standard says it falls back to PNG. Your code asked for WebP, received a PNG, and if you name the file photo.webp, the user downloads a PNG with the wrong extension.
The Blob tells you the truth in its type property, so compare it with what you asked for:
if (blob.type !== format) {
throw new Error(`This browser can't create ${format} files. Try another format or browser.`);
}
There is also a cheap way to test support up front, before the user converts anything. A 1×1 canvas exported with toDataURL reveals the format the browser produced:
function canEncode(type: string): boolean {
const c = document.createElement("canvas");
c.width = c.height = 1;
return c.toDataURL(type).startsWith(`data:${type}`);
}
With that, you can disable the unsupported option in the interface and explain why, instead of failing after the user has picked their files. The converter on this site does both: it greys out any format your browser can't create, and it checks every result's blob.type before offering the download.
Converting a batch without freezing the page
The converter accepts many files at once. Converting them one at a time, with await in a loop, keeps memory use predictable: only one full-size canvas exists at any moment.
for (const item of items) {
await convertItem(item);
}
Running every conversion at once with Promise.all looks faster, but ten large photos means ten full-size canvases in memory together, and on a phone that can crash the tab. Each conversion updates its own row in the list as it finishes, so the page still feels responsive.
Downloads and memory cleanup
Each finished file gets its own object URL, which becomes a normal download link:
const outUrl = URL.createObjectURL(blob);
const outName = `${baseName(file.name)}.webp`;
<a href={outUrl} download={outName}>download</a>
Object URLs keep their data alive until you release them. A tool that converts dozens of large images will hold all of them in memory unless it cleans up. The converter tracks every URL it creates and revokes it when it is no longer needed: when a file is removed from the list, when the list is cleared, when a file is converted again, and when the component unmounts.
const urls = new Set<string>();
function track(url: string) {
urls.add(url);
return url;
}
function release(url: string | null) {
if (url && urls.has(url)) {
URL.revokeObjectURL(url);
urls.delete(url);
}
}
// React: revoke everything when the tool unmounts
useEffect(() => () => urls.forEach((u) => URL.revokeObjectURL(u)), []);
"Download all" creates a temporary link for each converted file and clicks it. Some browsers ask the user once for permission to download several files, which is expected.
When the canvas approach is not enough
The built-in encoder is the right choice for a quick converter, but it has limits:
- No encoder settings. You get one quality number and the browser's defaults. There are no options like lossless WebP or effort levels.
- No metadata. Drawing to a canvas drops EXIF data such as camera details and location. For privacy that is a feature; for a photographer it may be a bug.
- Browser differences. Support for encoding some formats varies, which is why the
blob.typecheck above matters.
If you need more control, WebAssembly builds of real encoders exist, such as the codecs from the jSquash project or webp-wasm. They run in the browser too, so you keep the privacy benefit, at the cost of a larger download.
Frequently asked questions
Can JavaScript convert JPG to WebP without a server?
Yes. Load the file into an image, draw it on a canvas, and call canvas.toBlob(callback, "image/webp", quality). Everything happens on the user's device.
Is toBlob or toDataURL better for image conversion?
toBlob for real files. It gives you binary data directly, while toDataURL builds a base64 string about a third larger, which is slower and uses more memory for big images. toDataURL is fine for tiny tests like the 1×1 support check.
Why does my transparent PNG turn black when converted to JPEG?
JPEG has no transparency, so transparent pixels are encoded as black. Fill the canvas with a background colour, usually white, before drawing the image.
What quality should I use for WebP?
There is no universal answer. Something around 0.8 is a common starting point for photos; compare the result and the file size, and adjust. My converter defaults to 0.82 and lets you change it.
Does converting in the browser keep EXIF data?
No. The canvas only holds pixels, so camera details, timestamps and GPS location are dropped from the output. That is good for privacy, but use a different tool if you need to keep the metadata.
Try it
You can use the converter for free at /tools/image-converter: drop in some images, pick WebP and compare the sizes. More of what I write about the web is on the Writing page, including how this site serves one blog in four different designs.