Package

purescript-puregrain

Repository
roman-mkh/puregrain
License
MIT
Uploaded by
pacchettibotti
Published on
2026-11-29T21:58:54Z

Exact dithering, from library to browser: a library, a command-line tool and a web app that give the same pixels, for classic error diffusion and authentic 8-bit screens alike.

CI Pursuit npm npm downloads License: MIT Try online: puregrain lab

Dithering for pictures: error diffusion with 13 kernels, Ostromoukhov's and Zhou–Fang's among them, ordered (Bayer) dithering, retro palettes, and the screens of the ZX Spectrum and the Commodore 64, written as the machines' own files. Written in PureScript, with the same results everywhere: a library, a command-line tool and a web app.

A scarlet macaw's head three times: the original photo, dithered to 16 colors, and to black and white; under each, a circle magnifies the eye seven times, where the single pixels show

The macaw from the sample picture: as it is, dithered to the PC's 16 colors (CGA), and to black and white, both with Floyd–Steinberg. The circles magnify the eye seven times. Made with the command-line tool, without installing anything (Node.js 22 or later):

npx puregrain macaw-and-toucan.png colors.png --palette cga16
npx puregrain macaw-and-toucan.png bw.png --palette bw

To run them, save the picture first, or download it with curl -LO https://raw.githubusercontent.com/roman-mkh/puregrain/master/pictures/macaw-and-toucan.png (in Windows PowerShell, curl.exe).

Ways to use it

All of them run the same library, so the same settings give the same pixels.

Ready to use:

  • In the browser: puregrain lab, with nothing to install; the picture stays on your computer, and a machine's screen can be saved as the machine's own files too. How to use it: web/README.md.
  • On the command line: the npm package puregrain, for Node.js 22 or later, with npx as above or installed with npm install --global puregrain. Its page: npm/README.md; every option: cli/README.md, which also shows how to run it from a checkout of this repository.

As a library, in your own application:

  • In PureScript: spago install puregrain, then

    import Puregrain as P
    
    dithered = P.ditherImage P.floydSteinberg (P.threshold 128.0) image

    See Getting started with the library below, and the API reference on Pursuit.

  • Later: a JavaScript and TypeScript API on npm, for Node and the browser, and a web component on top of it (TODO.md).

Status: 0.x, before 1.0. The library, the command-line tool and puregrain lab work and are tested. Before 1.0, a breaking change raises the minor version (0.3 → 0.4); CHANGELOG.md lists the changes of the library and the tool.

What it does

  • Error diffusion with a choice of kernel: Floyd–Steinberg, Atkinson, Jarvis–Judice–Ninke, Stucki, Burkes, three Sierras, Fan and two by Shiau and Fan, or your own (a list of neighbour offsets and weights, checked when you build it); every row left to right, or serpentine, every other row right to left. See docs/error-diffusion.md.
  • Weights by tone: Ostromoukhov's variable-coefficient error diffusion, one set of weights per gray, for even patterns in flat areas, and Zhou and Fang's, which adds a threshold raised by noise against the patterns that remain in the mid-tones. See docs/weights-by-tone/.
  • Grayscale and color. For color there are two approaches:
    • dither each channel on its own, e.g. 4 levels per channel;
    • or pick the nearest color from a palette, looking at the whole pixel.
  • Ordered (Bayer) dithering: Bayer matrices of any power-of-2 size, or your own threshold map; on its own, or combined with error diffusion. See docs/ordered-dithering.md.
  • Linear light, when you want it: a gamma (sRGB's curve, or 1.2, 1.5 or 1.8) makes the dithering keep the light a screen gives off, not the average of the stored values; off by default. Its arithmetic is exact, so the library, the command-line tool and puregrain lab give the same results on every JavaScript engine. See docs/gamma.md.
  • Ready-made palettes: black & white, web-safe, CGA/EGA/VGA, ANSI 16/256 (xterm), Commodore 64, ZX Spectrum. Every palette's values are checked against a cited source. See docs/palettes.md.
  • Machine screens: the real look of 8-bit machines whose cells allow only a few colors: the ZX Spectrum and the Commodore 64's hires mode, two colors per 8×8 cell, with ordered dithering or error diffusion inside the cells. Written as a PNG, or as the machine's own files: the Spectrum's screen file and a tape that loads it, a C64 program that shows the picture, and an Art Studio picture. See docs/machine-screens/.
  • In memory or as a stream (the library): dither a whole image at once, or a lazy stream of rows, each dithered only when it's needed, so only the rows in flight are in memory and the input can even be endless. Or go one row at a time from any source, a network stream for example, with your own loop.
  • Time grows linearly with the pixel count (measured up to 1024×1024). See docs/benchmarks-dithering.md.

When to use the library, and when not

Use it when:

  • You need dithering inside a PureScript program. Pure functions, written entirely in PureScript, with no native dependencies: it runs wherever JavaScript runs (Node, browsers).
  • Images are large or streamed. Rows are dithered one at a time, so memory stays small, and the source can be a file or a network stream.

Look elsewhere when:

  • Speed matters. It runs as plain JavaScript; timings per mode and kernel are in the benchmarks. For batches of large images or interactive use, a native tool such as ImageMagick is the better choice.
  • You need the best photo quality. Linear light (gamma) and serpentine scanning are there, but no perceptual color distance and no color profiles yet (see Limitations).

Getting started with the library

In your browser, without installing anything

Open the quick start in Try PureScript, the language's online editor, which has puregrain among its packages (the version in its package set, which can lag the latest release). It's the program below: change the kernel or the threshold, and compare.

Setting up PureScript

You need Node.js, the PureScript compiler and spago. The official Getting Started guide installs them; spago's documentation covers the current spago (the guide still shows the older spago.dhall files). Tools installed locally, with npm install --save-dev purescript spago, run through npx: npx spago init.

In your PureScript project

spago init                # only for a new project
spago install puregrain

If spago doesn't find puregrain, your project's package set is older than puregrain; spago upgrade moves the project to the latest set.

A first program: a small gray gradient, made in code, and the same gradient dithered to black and white with Floyd–Steinberg, both printed as text.

import Puregrain as P

-- | A small gray image: 8 rows of 32 pixels, from black (0.0) on the left
-- | to white (255.0) on the right.
gradient :: Array (Array Number)
gradient = Array.replicate 8 (map (\x -> toNumber x * 255.0 / 31.0) (Array.range 0 31))

main :: Effect Unit
main = do
  log "The original gradient (shown with 5 shades):"
  log (render gradient)
  log ""
  log "Dithered to black and white with Floyd-Steinberg:"
  log (render (P.ditherImage P.floydSteinberg (P.threshold 128.0) gradient))

ditherImage takes a kernel (where each pixel's rounding error goes), a quantizer (which values a pixel may take) and the image: an array of rows, each an array of pixels. Here a pixel is a gray Number from 0.0 (black) to 255.0 (white); for color, it's P.RGB. render turns an image into text; the whole program, ready to run, is QuickStart.purs. To compile it in your own project, also install the packages it imports: spago install arrays integers maybe strings. Run it with spago run -m Puregrain.Examples.QuickStart (in this repository, see examples/) and your terminal shows the gradient twice: in 5 shades of gray, then dithered to just black and white, as dots whose density follows the gray. The examples also compare more ways to dither the same gradient, and show how to try your own variations in the REPL.

The library works on arrays of pixels; reading and writing image files is up to your application (the command-line tool does it in Node, with pngjs).

Working on this repository

After npm install and npm run build:

npm test                  # the test suites of the library, the tool and the web UI
npm run check             # what CI runs: strict build, tests, end-to-end checks (needs Docker)
npm run generate-images   # test images in samples/

How work is done (branches, CI, releases): CONTRIBUTING.md.

Repository layout

Path What
src/, test/ The library (Puregrain.* modules; Puregrain.Internal.* are internal) and its tests
cli/ The command-line tool, a separate package that uses the library
npm/ The npm package puregrain, the command-line tool bundled: its manifest, its page and its build
examples/ Small example programs, among them the quick start above; a separate package
web/ puregrain lab, the web UI: the package puregrain-web, in Halogen
scripts/ Test-image generator, benchmark, benchmark chart, end-to-end checks of the CLI, of the npm package and, in three browsers, of the web UI, and the bundles' third-party notices
.github/workflows/ CI: build, tests and end-to-end checks on every push; on master also publishing the web UI on GitHub Pages; on version tags also the release checks and the GitHub Release
docs/ Documentation (below)
logo/ The logo, and the script that makes it with puregrain; under its own terms (see License)
pictures/ The sample picture, to try puregrain on: an AI-generated photo of two birds

The four packages live in one spago workspace and are built together.

Documentation

Document Contents
examples/README.md The example programs: what each shows, how to run them, the REPL
cli/README.md The command-line tool: installing, quick start, options, examples
npm/README.md The npm package's page: running the command-line tool from npm
web/README.md puregrain lab: using it, its settings as the tool's options, browsers, accessibility, development and the manual checklist
pictures/README.md The sample picture: what it shows, how to try it, where it comes from
docs/error-diffusion.md Error diffusion: the 11 kernels, their tables, names and sources, your own kernels, and serpentine scanning
docs/weights-by-tone/ Methods whose weights depend on the pixel's tone: Ostromoukhov's and Zhou–Fang's
docs/ordered-dithering.md Ordered (Bayer) dithering: thresholds, the matrices, combining it with error diffusion
docs/gamma.md Gamma and linear light: the five values, which for which view, measured, and the engine check
docs/exact-arithmetic.md Why the light curves give the same bits on every JavaScript engine, and how
docs/palettes.md The preset palettes: values, sources, equivalences
docs/machine-screens/ Machine screens: dithering with cells, which mode for which picture; one page per machine, the ZX Spectrum and the Commodore 64
docs/test-images.md The generated test images, and what to look for in the results
docs/benchmarks-dithering.md Current performance, per mode and kernel
docs/benchmarks-fifo.md History: how an O(N³) slowdown was found and fixed
CLAUDE.md Design decisions and their reasons (kept up to date for the AI assistant used in development)
CHANGELOG.md Changes to the library and the command-line tool, per version
CONTRIBUTING.md How work is done: setup, branches, CI, versions, releases
TODO.md Open work and ideas

License

MIT: use it in any project, open or closed, free or commercial; keep the copyright and license notice. See LICENSE.

The logo is the exception. It was dithered by puregrain itself, in the colors of the ZX Spectrum and the Commodore 64, but it isn't under MIT: its own terms let you use it to refer to puregrain, not as your own project's logo. See logo/LICENSE.md.