Online forms and APIs often reject an image for being 21 KB when the limit is 20 KB. The usual advice — "lower the quality slider" — is vague, and sending the file to a compression API means the photo leaves the device. You can do the job entirely in the browser: draw the image to a canvas, encode it with toBlob, and search for the highest quality that still fits under the limit.

This article walks through that approach, including the case where even the lowest quality setting is still too large, and when WebP is a better encoding than JPEG.

Why canvas encoding is a new file

A JPEG from a phone is already compressed. Opening it and saving it again does not "compress it more" in a predictable way. What HTMLCanvasElement.toBlob() does is decode the pixels, then re-encode them from scratch with a quality parameter in the range 0 to 1. The output is a new Blob. Its size is the number you care about.

The quality parameter is not a file-size percentage. Quality 0.8 is not "80% of the original bytes." It is a hint to the encoder, and the resulting byte count depends on resolution, detail, and the browser's encoder. That is why you measure blob.size after each encode instead of guessing a quality value. createImageBitmap() is the cleanest way to decode the input file before you draw it.

A quality binary search

You want the highest quality whose encoded size is still <= targetBytes. Size is roughly monotonic in quality — it occasionally wiggles, but not enough to ruin a search — so about 10–12 iterations is enough. Quality is only meaningful to a couple of decimal places in practice.

function canvasToBlob(canvas, type, quality) { return new Promise((resolve, reject) => { canvas.toBlob( (blob) => (blob ? resolve(blob) : reject(new Error("toBlob failed"))), type, quality ); }); } async function searchQuality(canvas, type, targetBytes, minQ = 0.05, maxQ = 0.95) { const floor = await canvasToBlob(canvas, type, minQ); if (floor.size > targetBytes) { return { blob: null, quality: null, floorSize: floor.size }; } let lo = minQ; let hi = maxQ; let best = { blob: floor, quality: minQ }; for (let i = 0; i < 12; i++) { const mid = (lo + hi) / 2; const blob = await canvasToBlob(canvas, type, mid); if (blob.size <= targetBytes) { best = { blob, quality: mid }; lo = mid; // room to raise quality } else { hi = mid; } } return best; } 

A few practical details:

  • Always test the low end first. If quality 0.05 still overshoots the target, further searching quality is wasted work. You have to reduce pixel dimensions.
  • Keep the best blob that already fit, rather than encoding again at lo after the loop. Encoders are deterministic enough within one browser, but not worth a surprise on the last write.
  • Do not use toDataURL. It returns a base64 string, which uses more memory, and its length is not the file size (it is about 4/3 of the bytes, plus a prefix).

When quality is not enough: scale the image

A 4000×3000 phone photo cannot be squeezed into 20 KB at any JPEG quality without first shrinking the pixel grid. File size scales roughly with pixel count, so a 50% scale (one quarter of the pixels) is a much larger lever than a quality tweak.

Once the quality floor fails, binary-search a scale factor too:

async function loadToCanvas(file) { const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); const canvas = document.createElement("canvas"); canvas.width = bitmap.width; canvas.height = bitmap.height; const ctx = canvas.getContext("2d", { alpha: false }); ctx.drawImage(bitmap, 0, 0); bitmap.close(); return canvas; } function scaledCanvas(source, scale) { const width = Math.max(1, Math.round(source.width * scale)); const height = Math.max(1, Math.round(source.height * scale)); const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const ctx = canvas.getContext("2d", { alpha: false }); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high"; ctx.drawImage(source, 0, 0, width, height); return canvas; } async function compressToTarget(file, targetBytes, type = "image/jpeg") { const source = await loadToCanvas(file); const atFull = await searchQuality(source, type, targetBytes); if (atFull.blob) { return { ...atFull, scale: 1, width: source.width, height: source.height }; } let lo = 0.05; let hi = 1; let best = null; for (let i = 0; i < 10; i++) { const scale = (lo + hi) / 2; const frame = scaledCanvas(source, scale); const result = await searchQuality(frame, type, targetBytes); if (result.blob) { best = { ...result, scale, width: frame.width, height: frame.height }; lo = scale; // try larger dimensions } else { hi = scale; } } if (!best) { throw new Error(`Cannot fit ${type} under ${targetBytes} bytes even at minimum scale`); } return best; } 

The first call tries full resolution. If that already fits, you stop and keep all the pixels. Only if it does not fit do you search downward. After a mid-scale encode succeeds, you raise lo so the next guess is larger, not smaller. That keeps the output as sharp as the byte budget allows.

Round dimensions to integers. Snapping to multiples of 8 can help JPEG slightly (8×8 blocks), but the effect is small compared with choosing the right scale.

WebP versus JPEG

toBlob accepts "image/jpeg" and, in every current major browser, "image/webp". It does not meaningfully accept a quality argument for "image/png" — PNG is lossless, and the quality parameter is ignored. If you need a small PNG, you need a specialized encoder, or you need to admit that PNG is the wrong format for a photograph.

At a similar visual quality, WebP is often noticeably smaller than JPEG. Tight 20 KB and 50 KB budgets are much more likely to succeed with WebP at a usable resolution. web.dev's notes on WebP and image performance, plus MDN's image file type and format guide, cover when each format is appropriate.

The trade-off is compatibility. Many government and exam portals still only accept JPEG, and sometimes PNG. Read the accept list first. A practical sequence:

  1. If WebP is allowed, run the search with type = "image/webp" and keep the result if it fits.
  2. Otherwise use "image/jpeg".
  3. If you are unsure, produce both and compare blob.size and a side-by-side preview.

You can also convert an existing JPEG to WebP in the browser, then run the size search on that encoding. If you just need that conversion done locally, JPG to WebP does it in the current tab without uploading the file.

Orientation, color, and other silent changes

Re-encoding through a canvas is not a lossless round trip, even at quality 0.95.

  • Orientation. Phone photos often store a rotation in EXIF and keep the pixel grid unrotated. A canvas will draw the unrotated grid unless you honor the tag. createImageBitmap(file, { imageOrientation: "from-image" }) handles this in current browsers. Without it, a portrait photo can come out on its side.
  • Metadata. EXIF, GPS, and IPTC are dropped. That is usually what you want for a form upload. It also means you should not use this pipeline if you need to preserve copyright tags or a color profile.
  • Color. The canvas is typically sRGB. A photo with a wide-gamut Display P3 profile may shift slightly.
  • Alpha. JPEG cannot store transparency. Use alpha: false on the context for photographic JPEGs so the encoder is not fighting a pointless alpha channel. WebP can store alpha; only keep it if you need it.
  • Animation. A canvas draw uses a single frame. Animated WebP or GIF will be flattened.

Running the work off the main thread

Encoding a 12-megapixel image ten to twenty times will hitch the UI on the main thread. Move it to a worker with OffscreenCanvas: transfer an ImageBitmap, draw into new OffscreenCanvas(width, height), and call convertToBlob({ type, quality }) instead of toBlob. Feature-detect both APIs and fall back to the main thread if needed (Safari caught up only in recent versions).

A realistic 20 KB budget

Twenty kilobytes is a harsh limit for a photograph. A usable result is usually a small JPEG or WebP, perhaps 400–800 pixels on the long side, at a mid-to-low quality. Faces survive if you crop tightly before you shrink. Fine print and busy backgrounds do not.

If you are not writing this into an app and just need a single file under a published limit, a browser-only compressor that targets 20 KB and processes the file locally is enough. For that common cap, compress an image to 20 KB does the work on the device; the same idea applies to 50 KB, 200 KB, and 1 MB targets.

Before you upload, check the byte size in Finder or Explorer properties (not "size on disk"), the pixel dimensions if the form caps those, and the real format in the file header — some browsers will let you download a WebP named .jpg, and a strict form will reject it.

What this method will not do

Browser encoders are good, not world-class. MozJPEG or a search scored by SSIM will sometimes beat toBlob at the same byte count, usually via WebAssembly. For form uploads, the native encoder is close enough, with no server and no copy of the photo leaving the machine.

The pattern is: decode with orientation correction, search quality, then search scale, prefer WebP when the recipient allows it, and keep large jobs off the UI thread. Measure blob.size every time. The limit is a number, not a quality slider.