2.4 KiB
Quantise
(no submodules)
Purpose
Reduce an RGBA pixel buffer to a target number of colours using the image-q library. This module is the primary quantisation entry point, supporting three palette-generation algorithms and three dithering modes. It wraps the low-level image-q API with ergonomic options, Zod validation, and OpenTelemetry instrumentation.
Features
- Wu quant (median-cut, best quality)
- Neuquant (neural network, good for photos)
- RGBQuant (fastest, good for previews)
- Euclidean, Manhattan, and CIEDE2000 distance formulas
- Floyd-Steinberg and Riemersma dithering
- Zod option validation
- OTel counter and histogram instrumentation
Usage: Basic Example
import { quantise } from "@suaveplan/image-quantisation/quantise";
const result = quantise(pixels, 32, 32, {
colours: 16,
algorithm: "wuquant",
});
console.log(result.paletteSize); // ≤ 16
Usage: Advanced Example
import { quantise } from "@suaveplan/image-quantisation/quantise";
const result = quantise(pixels, 64, 64, {
colours: 32,
algorithm: "neuquant",
distance: "ciede2000",
dither: "floyd-steinberg",
});
// result.pixels is a new Uint8Array with quantised colours
// result.palette is the generated colour table
API Reference
quantise(pixels, width, height, options?): QuantiseResult
pixels— RGBAUint8Arraywidth,height— image dimensionsoptions—QuantiseOptions(optional)
Throws QuantisationError on invalid input dimensions, mismatched buffer size, or invalid options.
quantiseAdaptive(pixels, width, height, recommendedColours, recommendDithering, overrides?): QuantiseResult
Convenience wrapper that sets algorithm to "wuquant" and dither based on the boolean flag. overrides can override any individual field.
Implementation Notes
The function validates inputs with Zod schemas before delegating to image-q. OTel instruments are lazily initialised on first use to avoid side effects at module load time. All algorithms run synchronously. The mapDither helper translates our dither enum values into the strings expected by image-q. Performance varies by algorithm: Wu quant is generally the best balance of quality and speed, Neuquant excels on photographic content, and RGBQuant is fastest but may produce slightly lower quality. Callers should benchmark on their specific image corpus to choose the best algorithm.