# Dithering

Category: algorithms
Published: 2026-11-22
Tags: algorithm, dithering, image, tool

Open a picture with the image button, or drop one on the canvas, and it's redrawn with only the colours of the palette you pick. **Your image stays on your device**: it's processed in this page and never uploaded anywhere. The save button gives you the result as a PNG at the picture's own size.

The sample is my [Cloud Architecture](/photography/cloud-architecture/) photo.

## Few colours, many tones

A screen can show millions of colours, but a lot of printing, old hardware and plenty of good-looking design can't, or chooses not to. Dithering is how you fake the missing ones: put the colours you do have next to each other in a pattern fine enough that the eye blends them back into the tone in between. A grey made only of black and white is a scatter of black and white dots, more white where it's lighter.

The question is where to put the dots, and that's what the methods here answer differently:

1. **Ordered (Bayer)**: every pixel is compared against a threshold from a small repeating grid, the Bayer matrix, built so that neighbouring thresholds are as different as possible. It's fast, each pixel is decided on its own, and it gives that regular crosshatch look. The 8×8 grid has more steps of tone than the 4×4, and a finer pattern.
1. **Error diffusion**: go through the picture pixel by pixel, round each one to the nearest colour you have, and hand the part that rounding lost to the neighbours that haven't been done yet. Floyd–Steinberg (1976) passes on all of it, which keeps every tone faithful and looks organic. Atkinson's version, from the original Macintosh, only passes on three quarters, so highlights and shadows go clean white and black: punchier, a bit of detail lost.
1. **Gradient map**: no dots at all. Every tone becomes a colour along the palette, darkest to lightest, smoothly. It's the duotone look, and with Ink, Orange & Paper it's a quick way to make any photo look like it belongs on this site.

With more than two colours, the tones are spread evenly from the darkest colour to the lightest, and dithering happens between each pair of neighbours. **RGB, one bit** is different: it dithers red, green and blue each on their own, on or off, for the eight colours of the earliest colour screens.

**Pixel size** shrinks the picture before dithering, so each dot becomes a bigger block. Contrast and brightness are applied first, and matter more than they would in a normal photo editor: a dithered picture has so few levels that a small change moves a lot of dots.

## Source (sketch.js)

```javascript
'use strict'

// Dithering and gradient maps: turn any picture into a few flat colours.
// Open an image (or drop one on the canvas) and it's redrawn using only
// the colours of the chosen palette, either by dithering (a pattern of
// those colours that the eye blends back into tones) or as a gradient map
// (each tone swapped for a colour along the palette). Everything happens
// in this page: the picture is never uploaded anywhere.

// Avoiding Global Mode: https://github.com/processing/p5.js/wiki/Global-and-instance-mode
const experiment = ( sketch ) => {
  //
  // Configuration
  //
  let container = document.getElementById('sketch-holder')
  let canvas_el

  const SAMPLE = '/content/creative-code-lab/algorithms/dithering/images/sample.webp'
  const MAX_EDGE = 1600            // Longest edge worked on, in source pixels; bigger pictures are scaled down first

  let mode = 'floyd_steinberg'
  let palette_name = 'ink_orange_paper'
  let pixel_size = 2               // Size of one output pixel, in source pixels
  let contrast = 0                 // -100 to 100
  let brightness = 0               // -100 to 100
  let invert = false

  // Palettes, darkest first. ink, paper and orange are the site's own.
  const palettes = {
    ink_paper: { label: 'Ink & Paper', colors: ['#0a0a0a', '#f5f5f5'] },
    ink_orange_paper: { label: 'Ink, Orange & Paper', colors: ['#0a0a0a', '#ff6600', '#f5f5f5'] },
    ink_orange: { label: 'Ink & Orange', colors: ['#0a0a0a', '#ff6600'] },
    greys: { label: 'Four Greys', colors: ['#0a0a0a', '#5a5a5a', '#a8a8a8', '#f5f5f5'] },
    rgb: { label: 'RGB, one bit', colors: null } // each channel on or off: eight colours
  }

  const modes = {
    bayer_4: 'Ordered, Bayer 4×4',
    bayer_8: 'Ordered, Bayer 8×8',
    floyd_steinberg: 'Error diffusion, Floyd–Steinberg',
    atkinson: 'Error diffusion, Atkinson',
    gradient_map: 'Gradient map'
  }

  // The source, scaled to MAX_EDGE, and the result at one pixel per output pixel
  let source_canvas = document.createElement('canvas')
  let source_context = source_canvas.getContext('2d', { willReadFrequently: true })
  let output_canvas = document.createElement('canvas')
  let output_context = output_canvas.getContext('2d')
  let source_name = 'sample'
  let pending = false

  // Controls
  let controls = {
    open: document.getElementById("experiment-control-open"),
    reset: document.getElementById("experiment-control-reset"),
    save: document.getElementById("experiment-control-save"),
    fullscreen: document.getElementById("experiment-control-fullscreen-toggle"),
    mode: document.getElementById("experiment-control-mode"),
    palette: document.getElementById("experiment-control-palette"),
    pixel_size: document.getElementById("experiment-control-pixel-size"),
    pixel_size_label: document.getElementById("experiment-label-pixel-size"),
    contrast: document.getElementById("experiment-control-contrast"),
    contrast_label: document.getElementById("experiment-label-contrast"),
    brightness: document.getElementById("experiment-control-brightness"),
    brightness_label: document.getElementById("experiment-label-brightness"),
    invert: document.getElementById("experiment-control-invert")
  }

  //
  // Loading pictures
  //

  function loadImage(src, name) {
    let image = new Image()
    image.onload = () => {
      let scale = Math.min(1, MAX_EDGE / Math.max(image.width, image.height))
      source_canvas.width = Math.round(image.width * scale)
      source_canvas.height = Math.round(image.height * scale)
      source_context.drawImage(image, 0, 0, source_canvas.width, source_canvas.height)
      source_name = name
      if (src.startsWith('blob:')) URL.revokeObjectURL(src)
      schedule()
    }
    image.src = src
  }

  // A file from the picker or a drop is read straight from the visitor's
  // disk into an object URL, local to this page
  function openFile(file) {
    if (!file || !file.type.startsWith('image/')) return
    loadImage(URL.createObjectURL(file), file.name.replace(/\.[^.]+$/, ''))
  }

  //
  // The processing
  //

  // Bayer threshold matrices, built by the usual doubling: each step
  // takes four copies of the last, scaled and offset in a 0 2 / 3 1 order
  function bayer(size) {
    let m = [[0]]
    while (m.length < size) {
      let n = m.length
      m = Array.from({ length: n * 2 }, (_, y) => Array.from({ length: n * 2 }, (_, x) =>
        4 * m[y % n][x % n] + [[0, 2], [3, 1]][Math.floor(y / n)][Math.floor(x / n)]))
    }
    return m.flat()
  }
  const BAYER_4 = bayer(4)
  const BAYER_8 = bayer(8)

  function hexToRgb(hex) {
    let n = parseInt(hex.slice(1), 16)
    return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
  }

  // Tone of a pixel, 0 to 1, after contrast, brightness and invert
  function toneMapper() {
    let c = contrast / 100, b = brightness / 100
    let factor = c >= 0 ? 1 / Math.max(1 - c * 0.95, 0.05) : 1 + c
    return v => {
      v = (v - 0.5) * factor + 0.5 + b
      v = Math.min(1, Math.max(0, v))
      return invert ? 1 - v : v
    }
  }

  function process() {
    pending = false
    if (!source_canvas.width) return

    let w = Math.max(1, Math.round(source_canvas.width / pixel_size))
    let h = Math.max(1, Math.round(source_canvas.height / pixel_size))
    output_canvas.width = w
    output_canvas.height = h
    // Shrinking the source with the browser's own scaler averages each block
    output_context.imageSmoothingEnabled = true
    output_context.imageSmoothingQuality = 'high'
    output_context.drawImage(source_canvas, 0, 0, w, h)
    let image = output_context.getImageData(0, 0, w, h)
    let data = image.data
    let tone = toneMapper()

    if (palette_name === 'rgb') {
      ditherChannels(data, w, h, tone)
    } else {
      let colors = palettes[palette_name].colors.map(hexToRgb)
      // Work on one tone per pixel (Rec. 709 luma), then colour it
      let tones = new Float32Array(w * h)
      for (let i = 0; i < w * h; i++) {
        tones[i] = tone((0.2126 * data[i * 4] + 0.7152 * data[i * 4 + 1] + 0.0722 * data[i * 4 + 2]) / 255)
      }
      if (mode === 'gradient_map') gradientMap(tones, data, colors)
      else ditherTones(tones, data, w, h, colors)
    }

    output_context.putImageData(image, 0, 0)
    sketch.redraw()
  }

  // Smooth: each tone becomes a colour part way between two palette stops
  function gradientMap(tones, data, colors) {
    let last = colors.length - 1
    for (let i = 0; i < tones.length; i++) {
      let position = tones[i] * last
      let k = Math.min(Math.floor(position), last - 1)
      let t = position - k
      for (let ch = 0; ch < 3; ch++) data[i * 4 + ch] = colors[k][ch] + (colors[k + 1][ch] - colors[k][ch]) * t
      data[i * 4 + 3] = 255
    }
  }

  // Each tone snaps to one of the palette's levels, spread evenly from
  // darkest to lightest, with the threshold or the error doing the dithering
  function ditherTones(tones, data, w, h, colors) {
    let levels = colors.length - 1
    let paint = (i, level) => {
      let c = colors[level]
      data[i * 4] = c[0]; data[i * 4 + 1] = c[1]; data[i * 4 + 2] = c[2]; data[i * 4 + 3] = 255
    }

    if (mode === 'bayer_4' || mode === 'bayer_8') {
      let [matrix, size] = mode === 'bayer_4' ? [BAYER_4, 4] : [BAYER_8, 8]
      let cells = size * size
      for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
        let i = y * w + x
        let threshold = (matrix[(y % size) * size + (x % size)] + 0.5) / cells - 0.5
        paint(i, Math.min(levels, Math.max(0, Math.round(tones[i] * levels + threshold))))
      }
      return
    }

    // Error diffusion: what rounding lost at one pixel is handed to its
    // neighbours ahead, so the average tone survives
    let spread = mode === 'atkinson'
      ? [[1, 0, 1 / 8], [2, 0, 1 / 8], [-1, 1, 1 / 8], [0, 1, 1 / 8], [1, 1, 1 / 8], [0, 2, 1 / 8]] // passes on only 3/4: punchier
      : [[1, 0, 7 / 16], [-1, 1, 3 / 16], [0, 1, 5 / 16], [1, 1, 1 / 16]]
    for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
      let i = y * w + x
      let level = Math.min(levels, Math.max(0, Math.round(tones[i] * levels)))
      let error = tones[i] - level / levels
      paint(i, level)
      for (let [dx, dy, weight] of spread) {
        let nx = x + dx, ny = y + dy
        if (nx >= 0 && nx < w && ny < h) tones[ny * w + nx] += error * weight
      }
    }
  }

  // One bit per channel, each channel dithered on its own
  function ditherChannels(data, w, h, tone) {
    for (let ch = 0; ch < 3; ch++) {
      let tones = new Float32Array(w * h)
      for (let i = 0; i < w * h; i++) tones[i] = tone(data[i * 4 + ch] / 255)
      let scratch = new Uint8ClampedArray(w * h * 4)
      ditherTones(tones, scratch, w, h, [[0, 0, 0], [255, 255, 255]])
      for (let i = 0; i < w * h; i++) data[i * 4 + ch] = scratch[i * 4]
    }
    for (let i = 0; i < w * h; i++) data[i * 4 + 3] = 255
  }

  // Controls fire many input events a second; work once per frame at most
  function schedule() {
    if (pending) return
    pending = true
    requestAnimationFrame(process)
  }

  //
  // Control Handling
  //

  function setupControls() {
    Object.entries(modes).forEach(([key, label]) => controls.mode.add(new Option(label, key, false, key === mode)))
    Object.entries(palettes).forEach(([key, p]) => controls.palette.add(new Option(p.label, key, false, key === palette_name)))
    ;[[controls.pixel_size, 1, 12, 1, pixel_size], [controls.contrast, -100, 100, 1, contrast], [controls.brightness, -100, 100, 1, brightness]]
      .forEach(([input, min, max, step, value]) => { [input.min, input.max, input.step, input.value] = [min, max, step, value] })
    controls.invert.checked = invert
    updateLabels()
    updateFullscreenIcon()
  }

  function updateLabels() {
    controls.pixel_size_label.textContent = pixel_size
    controls.contrast_label.textContent = contrast
    controls.brightness_label.textContent = brightness
  }

  function showIcon(button, name) {
    button.querySelectorAll('svg').forEach(icon => {
      icon.classList.toggle('hidden', !icon.classList.contains(`icon-${name}`))
    })
  }

  function updateFullscreenIcon() {
    showIcon(controls.fullscreen, document.fullscreenElement ? 'compress' : 'expand')
  }

  function installControlHandlers() {
    controls.open.addEventListener('change', event => openFile(event.target.files[0]))
    controls.reset.addEventListener('click', () => loadImage(SAMPLE, 'sample'))

    controls.mode.addEventListener('change', event => { mode = event.target.value; schedule() })
    controls.palette.addEventListener('change', event => { palette_name = event.target.value; schedule() })
    controls.pixel_size.addEventListener('input', event => { pixel_size = parseInt(event.target.value); updateLabels(); schedule() })
    controls.contrast.addEventListener('input', event => { contrast = parseInt(event.target.value); updateLabels(); schedule() })
    controls.brightness.addEventListener('input', event => { brightness = parseInt(event.target.value); updateLabels(); schedule() })
    controls.invert.addEventListener('change', event => { invert = event.target.checked; schedule() })

    // Saved at the picture's own size, each output pixel a crisp block
    controls.save.addEventListener('click', () => {
      let full = document.createElement('canvas')
      full.width = output_canvas.width * pixel_size
      full.height = output_canvas.height * pixel_size
      let context = full.getContext('2d')
      context.imageSmoothingEnabled = false
      context.drawImage(output_canvas, 0, 0, full.width, full.height)
      full.toBlob(blob => {
        let link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `${source_name}_${mode}_${palette_name}_${pixel_size}px.png`
        link.click()
        setTimeout(() => URL.revokeObjectURL(link.href), 1000)
      }, 'image/png')
    })

    controls.fullscreen.addEventListener('click', () => {
      sketch.fullscreen(!document.fullscreenElement)
    })

    document.addEventListener('fullscreenchange', () => {
      updateFullscreenIcon()
      sketch.windowResized()
    })

    // Drop a picture anywhere on the canvas
    container.addEventListener('dragover', event => event.preventDefault())
    container.addEventListener('drop', event => {
      event.preventDefault()
      openFile(event.dataTransfer.files[0])
    })
  }

  //
  // P5.js touchpoints
  //
  sketch.setup = () => {
    canvas_el = sketch.createCanvas(container.clientWidth, container.clientHeight)
    canvas_el.parent(container)
    sketch.noLoop() // Nothing moves: draw only when something changes
    setupControls()
    installControlHandlers()
    loadImage(SAMPLE, 'sample')
  }

  sketch.windowResized = () => {
    sketch.resizeCanvas(container.clientWidth, container.clientHeight)
    sketch.redraw()
  }

  // Fit the result into the canvas, without smoothing, so each output
  // pixel stays a hard-edged block at any size
  sketch.draw = () => {
    sketch.background(10)
    if (!output_canvas.width) return
    let scale = Math.min(sketch.width / output_canvas.width, sketch.height / output_canvas.height)
    let w = output_canvas.width * scale, h = output_canvas.height * scale
    let context = sketch.drawingContext
    context.imageSmoothingEnabled = false
    context.drawImage(output_canvas, (sketch.width - w) / 2, (sketch.height - h) / 2, w, h)
  }
}

// Wait for everything to load
if (document.readyState === 'complete') {
  new p5(experiment)
} else {
  window.addEventListener('load', () => new p5(experiment))
}

```
