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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1createImageBitmap plus a canvas lets you resize and re-encode images entirely on the client, no server round-trip.
- 2Wrapping the callback-based toBlob in a Promise makes the async encoding step await-friendly.
- 3Guarding against a larger output means compression never makes a file worse than the original.
Related explainers
javascript
const express = require('express'); const multer = require('multer'); const path = require('path'); const crypto = require('crypto');
Safe image uploads with Multer in Express
file-upload
multer
validation
Intermediate
7 steps
javascript
const express = require('express'); const jwt = require('jsonwebtoken'); const crypto = require('crypto');
Refresh token rotation in Express
jwt
token-rotation
authentication
Advanced
9 steps
javascript
class StarRating { constructor(container, { max = 5, value = 0, onChange } = {}) { this.container = container; this.max = max;
Building an accessible star-rating widget
dom
event-handling
accessibility
Intermediate
7 steps
javascript
const form = document.querySelector('#signup-form'); const password = form.querySelector('#password'); const confirm = form.querySelector('#confirm-password'); const submit = form.querySelector('button[type="submit"]');
Live password-match validation in the DOM
form-validation
dom-events
accessibility
Intermediate
6 steps
javascript
const express = require('express'); const EventEmitter = require('events'); const router = express.Router();
Server-Sent Events with Express
server-sent-events
streaming
event-emitter
Advanced
8 steps
javascript
import { useState, useEffect, useCallback } from 'react'; export function useCountdown(initialSeconds) { const [secondsLeft, setSecondsLeft] = useState(initialSeconds);
Building a useCountdown hook in React
custom-hooks
state-management
side-effects
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/compressing-images-in-the-browser-with-canvas-explained-javascript-67d7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.