Skip to main content

Crate ditherlib

Crate ditherlib 

Source
Expand description

Ditherlib: image effects and dithering for Rust

Crates.io Documentation Rust CI Licence

Ditherlib is a Rust library for non-destructive image effects and dithering. Apply an effect to a whole image, a polygon, or a custom mask, then combine effects in an ordered pipeline when one pass is not enough.

Ditherlib effect showcase

§Table of contents

§Installation

cargo add ditherlib

Or add Ditherlib directly to Cargo.toml:

[dependencies]
ditherlib = "1"

JPEG and PNG support are enabled by default. See Codec features to select other formats.

§Quick start

Read an image, apply a black-and-white threshold, and write the result:

use ditherlib::{
    Renderer, Selection,
    effects::dither::{palette::Palette, threshold::Threshold},
    read, write,
};

fn main() -> ditherlib::Result<()> {
    let source = read("input.jpg")?;
    let effect = Threshold::new(Palette::black_and_white());
    let rendered = Renderer::new().render(&source, &effect, &Selection::All)?;

    write("output.png", &rendered)
}

The quick_start example is the runnable version.

§Core concepts

  • SourceImage owns immutable RGBA8 source pixels. Load one with read, or construct one from decoded pixels with SourceImage::from_rgba8.
  • An Effect describes one transformation. Effects can be reused across renders and configured through builder methods.
  • A Selection limits an effect to the whole image, an anti-aliased polygon, or a custom coverage mask.
  • Renderer applies effects and returns an owned RenderedImage. Reusing a renderer also reuses its internal working buffers.
  • Pipeline applies several selected effects in order. Every render begins from the unchanged source image.

The prelude collects common imports. Specific imports remain available under their effect families, such as effects::dither::diffusion::ErrorDiffusion.

§Effect catalogue

EffectPurpose
GreyscaleConvert RGB pixels to greyscale while preserving alpha.
BlurApply Gaussian blur with a configurable sigma.
ThresholdMap sampled logical pixels directly to a palette.
OrderedDitherDither with Bayer, artistic, blue-noise, or custom threshold maps.
NoiseDitherApply deterministic white-noise or blue-noise dithering.
HalftoneRender a palette through geometric print-style screens.
ColourHalftoneScreen RGB or CMYK channels independently.
ErrorDiffusionUse one of fourteen diffusion presets or a custom kernel.
OstromoukhovDitherApply tone-adaptive variable-coefficient diffusion.
RiemersmaDitherDiffuse error along a Hilbert curve.

Threshold, ordered, noise, error-diffusion, Ostromoukhov, and Riemersma effects share logical-pixel sizing, grid offsets, and sampling controls. The API documentation covers every parameter and validation rule.

§Palettes

Palette includes black-and-white, greyscale, Game Boy, CGA, PICO-8, and monochrome presets. You can also supply custom colours or derive a palette from a source image:

use ditherlib::{SourceImage, effects::dither::palette::{Palette, PaletteSize}};

fn palette_from(source: &SourceImage) -> ditherlib::Result<Palette> {
    Palette::from_source(source, PaletteSize::Limited(16))
}

Palette matching supports gamma-encoded RGB, linear RGB, and Oklab colour spaces, with full-colour or luminance-only matching. See the palettes example for built-in, custom, derived, and perceptual palettes.

§Selections

Use Selection::All for the whole image, Selection::Polygon for an anti-aliased geometric region, or Selection::Mask for custom per-pixel coverage. Polygons can be rectangles, centred squares, regular polygons, or arbitrary validated vertices.

The selections example shows whole-image and polygon rendering.

§Pipelines

A pipeline applies effects in insertion order, so each step receives the result of the previous step:

use ditherlib::{Pipeline, Renderer, Selection, SourceImage};
use ditherlib::effects::{
    blur::Blur,
    dither::{palette::Palette, threshold::{OrderedDither, ThresholdMap}},
    greyscale::Greyscale,
};

fn render(source: &SourceImage) -> ditherlib::Result<()> {
    let mut pipeline = Pipeline::new();
    pipeline.add(Greyscale, Selection::All);
    pipeline.add(
        OrderedDither::new(Palette::black_and_white(), ThresholdMap::bayer_4x4())
            .with_pixel_size(4, 4)?,
        Selection::All,
    );
    pipeline.add(Blur::new(1.5)?, Selection::All);

    Renderer::new().render_pipeline(source, &pipeline)?;
    Ok(())
}

Greyscale, ordered-dither, and blur pipeline applied to samurai armour

See the runnable pipeline example.

§Codec features

The default jpeg and png features can be replaced with any supported image codecs:

[dependencies]
ditherlib = { version = "1", default-features = false, features = ["png", "webp"] }

Available features are avif, bmp, dds, exr, ff, gif, hdr, ico, jpeg, png, pnm, qoi, tga, tiff, and webp. Processing algorithms compile without codec features when images are supplied through SourceImage::from_rgba8.

§Examples

Every example accepts an input path and output directory:

cargo run --release --example quick_start -- input.jpg output
ExampleDemonstrates
quick_startReading, thresholding, rendering, and writing.
ordered_ditherOrdered dithering with custom logical pixels.
error_diffusionFloyd-Steinberg, Ostromoukhov, and Riemersma.
halftoneMonochrome and colour halftones.
palettesBuilt-in, custom, derived, and perceptual palettes.
selectionsWhole-image and polygon selections.
pipelineA multi-effect rendering pipeline.
comparisonA visual overview of the major algorithm families.

§Benchmarks

The Criterion suite covers every effect and configuration family across deterministic in-memory fixtures. See the benchmark guide for the complete matrix, measurement boundaries, HTML reports, and baseline workflow.

§Minimum supported Rust version

Ditherlib requires Rust 1.88 or newer.

§Errors

Fallible operations return ditherlib::Result<T>. DitherError::kind() provides stable ErrorKind categories for matching, while the error display and source retain diagnostic detail. JPEG output discards alpha because the format does not support transparency.

§Licence

Licensed under the Apache License 2.0.

Example image attribution is recorded in the assets documentation.

Modules§

effects
Image effects grouped by algorithm family.
prelude
Convenient imports for applications that use several effect families.

Structs§

DitherError
An error returned by a Ditherlib operation.
Mask
Per-pixel selection coverage for an image.
Pipeline
An editable ordered collection of effects and their selections.
PipelineStep
One effect and selection in an ordered Pipeline.
Point
A point in image coordinates, with the origin at the top-left corner.
Polygon
A polygon selection boundary.
RenderedImage
A separately owned image produced by a Renderer.
Renderer
Evaluates effects without modifying their source image.
SourceImage
An image loaded into memory by Ditherlib.

Enums§

ErrorKind
A category describing why a Ditherlib operation failed.
Selection
An area of an image to which an effect can be applied.

Traits§

Effect
An image effect that can be evaluated by a Renderer.

Functions§

read
Reads and decodes an image from disk.
write
Encodes a rendered image to a file.

Type Aliases§

Result
A result returned by Ditherlib operations.