Repository navigation
Install
- Command-line tool: an archive below,
cargo binstall imgquantorcargo install imgquant - Rust:
cargo add libimgquant - Python:
pip install libimgquant - npm:
npm install libimgquant - C:
libimgquant-capiwith cargo-c, see the README
Overview
- Pure Rust: a rewrite of libimagequant 2.4.1 (tag
2.4.1, commit
976e021cda07c14cd36630f611a5a6eb2cafc28e) in Rust,#![forbid(unsafe_code)], with no C
code, no build script and no FFI. Dependencies:rgb,rayonfor the optional
threadsfeature (on by default) andpngfor the optionalpngfeature. MSRV 1.85. - License: BSD-2-Clause, plus Jef Poskanzer's original permissive notice. No code from
libimagequant 2.5 or later (GPL-3) was used.LICENSEhas the BSD-2-Clause text and
NOTICEthe provenance and Poskanzer's notice; every crate, wheel, sdist and the npm
package ships both. - Two profiles:
Profile::Improved(the default) uses the new algorithms below.
Profile::Compatreproduces 2.4.1 step by step, including its mixedf32/f64
arithmetic, apart from the bug fixes below; golden-hash tests freeze its output.
New algorithms (Profile::Improved)
- Color difference: an OKLab-shaped opponent matrix (lightness and two chroma axes) on
2.4.1's internal gamma, keeping its premultiplied alpha and black/white blending. - Median cut: splits along the principal axis at the error-optimal point, and splits
the box with the largest error first. - Refinement: weighted Hartigan moves after the k-means (Lloyd) iterations.
- Nearest color: an exact search with a switching triangle-inequality search.
- Dithering: serpentine Floyd-Steinberg in parallel 64-row strips with warm-up rows;
seamless and deterministic. - Palette order: colors that touch in the image get adjacent indices (speeds 1-7), which
makes filtered PNGs smaller. Translucent entries still come first. - Speed presets: fewer repeated median cuts and k-means iterations.
On the project's private 22-image test set at speed 3 without dithering (measured on
2026-10-22), the default profile takes 1.39 s against 4.73 s for the 2.4.1 port, scores
better on SSIMULACRA2, butteraugli and CIEDE2000, and gives 6% smaller PNGs (BENCHMARKS.md).
Faster in both profiles (output unchanged)
- The 2.4.1 nearest-color search is vectorized and prunes with the triangle inequality.
- With the
threadsfeature, the histogram, contrast maps, pixel conversion, k-means
iterations, remapping and dither map run in parallel. Parallel sums use fixed work
chunks, so output does not depend on the number of threads.
Rust API
Attributes,ImageandQuantizationResultreplaceliq_attr,liq_imageand
liq_result; errors areResult<_, Error>.- Images from owned or borrowed pixels (with or without a stride), separate rows, or a row
callback. - Remapping into a new buffer (
remapped), a contiguous buffer (remap_into) or separate
rows (remap_rows); one result can remap several images, each with the palette fitted to
it, whichremappedreturns. - Log callbacks are closures.
Histogram: one palette for several images (animation frames, sprite sheets). Images are
added withadd_image, weighted asquantizeweights a single image (contrast maps, each
color limited to a tenth of the image's area); colors with pixel counts with
add_colors(HistogramEntry); fixed colors withadd_fixed_color.quantizereturns a
result that remaps every image to exactly the same palette. All colors must have one
gamma. The result is the same for any number of threads.- Feature
png(off by default): thepng_iomodule decodes any PNG to RGBA with its gamma
and ICC profile (decode), writes palette PNGs with the smallest bit depth, a trimmed tRNS
chunk and the smaller of an unfiltered and a filtered encoding (encode_indexed), and
converts a PNG in one call (compress_png), keeping the gamma and ICC profile.
encode_indexedtakes the gAMA and iCCP chunks to write as aPngMetadata, which
DecodedPng::metadata()copies from a decoded file. The command-line tool uses it. decodeand untrusted files: images overi32::MAXpixels are rejected before anything
is allocated, the pixels are allocated fallibly and filled as rows are decoded, and
images with too little image data for their size fail before their pixels are allocated.
The png crate's own buffers keep its 64 MiB limit. Only RGB ICC profiles are written (PNG
allows no other kind on palette images).- Every public type implements
Debug;ImageandQuantizationResultshow their size
and settings, not their pixels. examples/animated_gif.rs: PNG frames (or a synthetic animation) to an animated GIF with
one palette, usingHistogramand thegifcrate (a development dependency only).
C API (libimgquant-capi, new crate)
libimgquant.hwith every function, type and constant of the libimagequant 2.4.1 header.
Programs written for 2.4.x need only a new include and-limgquant.- Builds a shared and a static library;
cargo cinstall(cargo-c) installs the header and
alibimgquant.pcpkg-config file. - Additions:
liq_set_profile/liq_get_profilewithLIQ_HAS_PROFILES, and a declared
liq_version().LIQ_VERSIONis 30000. liq_get_palettereturns one stable pointer per result, valid until
liq_result_destroy; in 2.4.1 an old pointer could dangle after remapping.liq_image_create_rgbareturns NULL when the image can't be created; 2.4.1 wrote through
a NULL pointer.
Command-line tool (imgquant, new crate)
- A pngquant-style command-line tool built on the library:
cargo install imgquant. - pngquant's options: number of colors,
--quality,--speed(1-11; 11 is the same as
10),--nofs/--ordered/--floyd,--posterize,--ext,-o,--force,
--skip-if-larger,--strip,--transbug,-v/-q; plus--profileand--threads.
--orderedis the same as--nofs, since there is no ordered dithering. - pngquant's exit codes: 99 when the minimum quality can't be reached, 98 when the result
would be larger (--skip-if-larger), 15 when the output exists without--force. With
standard output as the output, 98 and 99 write the input there unchanged. - Reads every PNG color type and bit depth, keeps the input's gamma and ICC profile
(--stripdrops the ICC profile), writes the smallest bit depth and the smaller of an
unfiltered and a filtered encoding, and writes files atomically. Reads standard input and
writes standard output with-. - Prebuilt binaries for Linux (static musl builds for x86_64 and aarch64), Windows (x64) and
macOS (arm64, x86_64) are attached to the GitHub release;cargo binstall imgquant
installs them.
npm package (libimgquant, new, wasm/)
- WebAssembly build for browsers and Node.js 18+, with TypeScript types and no
dependencies:quantize,compressPng(PNG in, smaller indexed PNG out) and
quantizeFrames(one palette for many frames). About 480 KB.wasm, 190 KB gzipped.
compressPngkeeps the input's gamma and ICC profile.
Python package (libimgquant, new, python/)
- PyO3 bindings with stable-ABI wheels for CPython 3.9+:
quantize,compress_png,
quantize_framesand the Pillow helperquantize_image. Accepts bytes, bytearray,
memoryview and numpy arrays; releases the GIL while working; raises
QualityTooLowErrorwhen the minimum quality can't be reached.compress_pngkeeps the
input's gamma and ICC profile. - The wheels and the sdist include
THIRD-PARTY-LICENSES.txt, the licenses of the Rust
crates compiled into the extension.
Bug fixes (both profiles)
- Edge map: high-contrast pixels no longer get garbage values (2.4.1 converted negative
floats to bytes with undefined behavior). - Large images: images over about 4 megapixels get correct contrast maps (2.4.1 reused
one row buffer for three rows, so it saw no vertical edges and shifted the map by a row). - Median cut: deep recursion, which could overflow the stack on large images with many
near-identical colors, is now iterative. - Out-of-bounds reads in rare edge cases are replaced with safe behavior.
- Settings:
set_dithering_levelvalidates the new value instead of the previous one,
andset_output_gammano longer returns a palette rounded with the previous gamma.
Deterministic output
- Dithering noise comes from the crate's own seeded generator (the lagged-Fibonacci
algorithm of GNUrandom()) instead of the globalrand(). - Sorting uses a fixed tie order instead of the platform's
qsortorder, and histogram
hashing is little-endian on every platform. - So output is identical on every platform. The dither map threshold is speed 5 in every
build; 2.4.1 raised it to 7 in OpenMP builds.