Image Processing in the Browser — WebAssembly

The image-processing flow with Wasm: getImageData from the canvas, copy the RGBA bytes into linear memory, call the Wasm function once for the whole photo…

The same Terrace Room photo, three versions: black and white for the photocopied brochure, small for the room list, and blurred for the booking page's background. All three can be made in the browser: take a photo's pixels from a canvas, compute new pixels, then draw them again. Wasm suits the computing part, because each photo holds millions of bytes that go through the same loop.

The work is like a small photo shop. The photo is carried from the shop window to a fast craftsman's table, worked on there, then carried back. If the craftsman works in the back room, the cashier at the front can keep serving guests. The shop window is the canvas, the craftsman's table is Wasm memory, carrying the photo back and forth is copying bytes, and the back room is a Web Worker.

The flow: canvas, Wasm memory, canvas again

This lesson uses photolab.wasm: a no_std Rust crate with grayscale, three ways to resize and a blur, 4,177 bytes after a release build. All its maths uses whole numbers, so its output matches the JavaScript version in the Lab byte for byte.

const ctx = canvas.getContext('2d', { willReadFrequently: true });
const img = ctx.getImageData(0, 0, 1200, 800); // RGBA, 3,840,000 bytes

WebAssembly.instantiate(bytes).then(({ instance }) => {
  const { memory, grayscale } = instance.exports;
  const ptr = memory.buffer.byteLength;           // put the photo after the module's initial memory
  memory.grow(Math.ceil(img.data.length / 65536)); // 59 more pages
  new Uint8Array(memory.buffer).set(img.data, ptr);                // copy in
  grayscale(ptr, img.data.length);                                 // compute in Wasm
  img.data.set(new Uint8Array(memory.buffer, ptr, img.data.length)); // copy out
  ctx.putImageData(img, 0, 0);
});

Why Wasm suits this: the photo has 960,000 pixels, and each one needs the same multiplications and additions. That is pure CPU work. Wasm reads and writes bytes directly in linear memory, with no objects and no garbage collector, and its compiled code is steady across browsers.

Grayscale, now with SIMD

The formula is the one from the earlier lessons: gray = (r × 77 + g × 150 + b × 29) >> 8. SIMD (single instruction, multiple data) runs one instruction on 16 bytes at once, so 4 pixels per step. Wasm has had 128-bit SIMD since Chrome 91, Firefox 89 and Safari 16.4.

#[unsafe(no_mangle)]
#[target_feature(enable = "simd128")]
pub unsafe extern "C" fn grayscale_simd(ptr: *mut u8, len: usize) {
    use core::arch::wasm32::*;
    let weights = i16x8(77, 150, 29, 0, 77, 150, 29, 0);
    let alpha = u32x4_splat(0xFF00_0000);
    let rgb = u32x4_splat(0x0001_0101); // gray × 0x010101 = gray in bytes R, G, B
    let mut i = 0;
    while i + 16 <= len {
        let p = unsafe { ptr.add(i) } as *mut v128;
        let v = unsafe { v128_load(p) };
        let a = i32x4_dot_i16x8(u16x8_extend_low_u8x16(v), weights);
        let b = i32x4_dot_i16x8(u16x8_extend_high_u8x16(v), weights);
        let sum = i32x4_add(i32x4_shuffle::<0, 2, 4, 6>(a, b), i32x4_shuffle::<1, 3, 5, 7>(a, b));
        let gray = u32x4_shr(sum, 8);
        unsafe { v128_store(p, v128_or(i32x4_mul(gray, rgb), v128_and(v, alpha))) };
        i += 16;
    }
    unsafe { grayscale(ptr.add(i), len - i) }; // leftover bytes: the plain version
}

Measured on a busy laptop, medians, in milliseconds (Chromium 147 / WebKit 26.4):

Grayscale 1200 × 800 Time
JavaScript 1.95 / 1.13
Wasm 0.85 / 0.88
Wasm, SIMD written by hand 0.47 / 0.44
Wasm, SIMD from the compiler 0.84 / 0.93

All three Wasm versions match JavaScript exactly. A module that contains SIMD instructions fails to compile on an engine without SIMD, so check first with WebAssembly.validate on a tiny module containing SIMD (the approach the wasm-feature-detect library uses), and ship two builds.

The 400 × 267 thumbnail: nearest, bilinear, area average

Before reading on, guess. The bamboo wall in the photo has slats 2 pixels wide, light and dark in turn. If the 1200 × 800 photo is shrunk to 400 × 267 with bilinear, does the wall become a flat colour, fake stripes, or the same as nearest?

1200 divided by 400 is exactly 3, so the centre of every thumbnail pixel lands right on original pixel 3x + 1. Bilinear's horizontal weight is 0, and the result is nearly the same as nearest: only 7,304 of 427,200 bytes differ. The bamboo wall (2-pixel slats, red values 150 and 105) is sampled every 3 pixels, and fake stripes appear, 3 times wider than the real ones. Bilinear only looks at 4 neighbours, so for a 3× shrink it is no better than nearest. This effect is called aliasing (moiré).

Method Chromium 147 Colour swing on the wall
Nearest, JS / Wasm 0.21 / 0.08 ms 22.5 (same as the original)
Bilinear, JS / Wasm 3.02 / 0.87 ms 22.5
Area average, JS / Wasm 5.62 / 2.07 ms 7.5
Blur σ 1.5 first, then bilinear 3.0

"Colour swing" is the standard deviation of the red values over the wall area: the smaller, the flatter, the more correct. To shrink a lot, average the area or blur first.

Blur: a computed kernel, two passes

A Gaussian blur replaces each pixel with a weighted average of its neighbours. The weights are computed from σ (sigma, the blur's width):

function kernelGauss(sigma) {
  const r = Math.ceil(sigma * 3); // neighbours up to 3σ away
  const w = [];
  let total = 0;
  for (let i = -r; i <= r; i++) {
    const v = Math.exp(-(i * i) / (2 * sigma * sigma));
    w.push(v);
    total += v;
  }
  const k = w.map((v) => Math.round((v / total) * 4096)); // whole-number weights that sum to 4096
  k[r] += 4096 - k.reduce((a, b) => a + b, 0);           // the rounding leftover goes to the centre
  return { k, r };
}
// kernelGauss(2).k = [9, 36, 111, 266, 496, 722, 816, 722, 496, 266, 111, 36, 9]
Gaussian blur σ 2 Chromium 147 WebKit 26.4
JavaScript 155 ms 127 ms
Wasm 49 ms 49 ms
Wasm, +simd128 build 37 ms 39 ms

Here Wasm is 2.6 to 3.2 times faster, because the computing far outweighs the cost of the copies.

Worker and OffscreenCanvas: the UI keeps going

A 49 ms blur on the main thread means a page frozen for 49 ms: clicks and scrolling wait. Move the computing into a Web Worker, and send the bytes as a transferable: the ArrayBuffer is moved, not copied.

// the page
const worker = new Worker('photo-worker.js');
worker.onmessage = (e) => ctx.putImageData(new ImageData(new Uint8ClampedArray(e.data), 1200, 800), 0, 0);
const img = ctx.getImageData(0, 0, 1200, 800);
worker.postMessage({ pixels: img.data.buffer, sigma: 2 }, [img.data.buffer]); // moved

// photo-worker.js: set up photolab.wasm once, blur, send back with a transfer too
onmessage = (e) => {
  const result = blurWithWasm(e.data.pixels, e.data.sigma); // a new ArrayBuffer
  postMessage(result, [result]);
};

Measured with a MessageChannel "heartbeat" on the main thread, the longest gap (median of 5 runs, Chromium 147 / WebKit 26.4):

σ 2 blur with Wasm Longest gap on the main thread Total (Chromium)
On the main thread 51 / 51 ms 51 ms
In a Worker, the page draws the result 1.5 / 8.6 ms 54 ms
In a Worker with OffscreenCanvas 0.7 / 6.5 ms 53 ms

The total is slightly longer, but the page never freezes. With canvas.transferControlToOffscreen(), the canvas is handed to the Worker, and the Worker draws on it itself. 2D OffscreenCanvas is in Chrome 69, Firefox 105 and Safari 16.4.

💡 When you don't need Wasm

⚠️ What makes the photo striped or the page freeze

TL;DR: The image-processing flow with Wasm: getImageData from the canvas, copy the RGBA bytes into linear memory, call the Wasm function once for the whole photo, copy the result out, putImageData. Wasm suits it because the work is pure CPU over millions of bytes, read straight from memory with no garbage collector. Grayscale of 1200 × 800 in Chromium 147: JS 1.95 ms, Wasm 0.85 ms, SIMD 0.47 ms (check support with WebAssembly.validate). A 400 × 267 thumbnail: nearest and bilinear both create fake stripes; area averaging or blurring first is right. Gaussian blur: the kernel is computed from σ (r = ceil(3σ), whole-number weights summing to 4096) and done in two passes (26 multiplications, not 169): JS 155 ms, Wasm 49 ms, +simd128 37 ms. Put heavy work in a Worker (the main-thread gap goes from 51 ms to 1.5 ms) and send the ArrayBuffer as a transferable, or hand the canvas over with OffscreenCanvas. For display only use a CSS filter, for an ordinary thumbnail createImageBitmap, for video WebGL or WebGPU, and for encoders such as MozJPEG or AVIF use the existing Wasm codecs (Squoosh, jSquash).

⚡ Canvas, Wasm memory, canvas again

Write:

new Uint8Array(memory.buffer).set(img.data, ptr);                // copy in
grayscale(ptr, img.data.length);                                 // compute in Wasm
img.data.set(new Uint8Array(memory.buffer, ptr, img.data.length)); // copy out
ctx.putImageData(img, 0, 0);

Meaning: Wasm cannot read a canvas. The RGBA bytes from getImageData are copied into linear memory first, Wasm is called once for the whole photo, then the result is copied out and drawn with putImageData.

⚡ SIMD: 4 pixels per step

Meaning: SIMD runs one instruction on 16 bytes at once. Grayscale of 1200 × 800 in Chromium 147 drops from 0.85 ms to 0.47 ms. An engine without SIMD rejects the whole module, so check first with WebAssembly.validate.

⚡ A 3× shrink makes fake stripes

Guess first: a bamboo wall with 2-pixel slats is shrunk from 1200 × 800 to 400 × 267 with bilinear. Does it become flat, fake stripes, or the same as nearest?

Fake stripes, 3 times wider than the real ones, and nearly the same as nearest. Bilinear only looks at 4 neighbours, so for a 3× shrink it is no better.

Meaning: To shrink a lot, average the area or blur first.

⚡ Blur in two passes, in a Worker

Write:

worker.postMessage({ pixels: img.data.buffer, sigma: 2 }, [img.data.buffer]); // moved

Meaning: A Gaussian blur runs horizontal then vertical: 26 multiplications per pixel, not 169. On the main thread, a 49 ms blur means a page frozen for 49 ms. In a Worker, the ArrayBuffer is moved as a transferable, not copied, and the page keeps going.

What you will learn