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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
7 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.