javascript 34 lines · 7 steps

Compressing images in the browser with canvas

A client-side helper that downscales and re-encodes an image file, returning a smaller File — or the original if it can't beat it.

Explained by highlit
1export async function compressImage(file, { maxWidth = 1600, maxHeight = 1600, quality = 0.8, mimeType = 'image/jpeg' } = {}) {
2 const bitmap = await createImageBitmap(file);
3 
4 let { width, height } = bitmap;
5 const ratio = Math.min(maxWidth / width, maxHeight / height, 1);
6 width = Math.round(width * ratio);
7 height = Math.round(height * ratio);
8 
9 const canvas = document.createElement('canvas');
10 canvas.width = width;
11 canvas.height = height;
12 
13 const ctx = canvas.getContext('2d');
14 ctx.imageSmoothingQuality = 'high';
15 ctx.drawImage(bitmap, 0, 0, width, height);
16 bitmap.close();
17 
18 const blob = await new Promise((resolve, reject) => {
19 canvas.toBlob(
20 (result) => (result ? resolve(result) : reject(new Error('Canvas is empty'))),
21 mimeType,
22 quality,
23 );
24 });
25 
26 if (blob.size >= file.size) {
27 return file;
28 }
29 
30 const extension = mimeType === 'image/webp' ? 'webp' : 'jpg';
31 const name = file.name.replace(/\.[^.]+$/, '') + '.' + extension;
32 
33 return new File([blob], name, { type: mimeType, lastModified: Date.now() });
34}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1createImageBitmap plus a canvas lets you resize and re-encode images entirely on the client, no server round-trip.
  2. 2Wrapping the callback-based toBlob in a Promise makes the async encoding step await-friendly.
  3. 3Guarding against a larger output means compression never makes a file worse than the original.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Compressing images in the browser with canvas — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code