1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//! # Dither
//! # Written by Efron Licht. Available under the MIT license. Hire me!
//!
//!
//! Inspired by: <http://www.tannerhelland.com/4660/dithering-eleven-algorithms-source-code/>
//! and the game "Return of the Obra Dinn"

/// handling of color modes & [color::rgb::RGB].
pub mod color;
pub mod ditherer;
mod error;
mod img;
mod opts;
pub mod prelude;
pub use self::error::Error;
pub use self::error::Result;

use self::prelude::*;
#[cfg(test)]
mod tests;

/// quantize to n bits. See the [bit_depth][crate::opts::Opt] option.
/// ```
/// # use dither::prelude::*;
/// # use dither::create_quantize_n_bits_func;
/// let one_bit = create_quantize_n_bits_func(1).unwrap();
/// let want = 0;
/// assert_eq!(one_bit(100.), (0., 100.));
/// assert_eq!(one_bit(250.), (255., -5.));
///
/// ```
pub fn create_quantize_n_bits_func(n: u8) -> Result<impl Fn(f64) -> (f64, f64)> {
    if n == 0 || n > 7 {
        Err(Error::BadBitDepth(n))
    } else {
        let step_size: f64 = 255. / f64::from(n);
        let quantize = move |x: f64| {
            debug_assert!(x.is_normal());
            let y = x / step_size;
            let (floor, ceil) = (y.floor() * step_size, y.ceil() * step_size);
            let (floor_rem, ceil_rem) = (x - floor, ceil - x);
            if floor_rem < ceil_rem {
                let quot = f64::max(floor, 0.0);
                (quot, floor_rem)
            } else {
                let quot = f64::min(255.0, ceil);
                (quot, -ceil_rem)
            }
        };
        Ok(quantize)
    }
}

/// clamp a f64 to the closest u8, rounding non-integers.
/// ```
/// # use dither::clamp_f64_to_u8;
/// assert_eq!(clamp_f64_to_u8(255.2), 255);
/// assert_eq!(clamp_f64_to_u8(2.8), 3);
/// ```
pub fn clamp_f64_to_u8(n: f64) -> u8 {
    match n {
        n if n > 255.0 => 255,
        n if n < 0.0 => 0,
        n => n.round() as u8,
    }
}
/// run dither using the provided options.
pub fn exec(opts: &Opt) -> Result<()> {
    let (input, output) = (&opts.input, opts.output_path()?);
    if opts.verbose {
        eprintln!(
            concat!(
                "running dither in VERBOSE mode:\n\t",
                "INPUT: {input}\n\t",
                "OUTPUT: {output}\n\t",
                "DITHERER: {dither}\n\t",
                "BIT_DEPTH: {depth}\n\t",
                "COLOR_MODE: {mode}"
            ),
            input = input.display(),
            output = output.display(),
            dither = opts.ditherer,
            depth = opts.bit_depth,
            mode = opts.color_mode,
        );
    }
    let img: Img<RGB<f64>> =
        Img::<RGB<u8>>::load(&input)?.convert_with(|rgb| rgb.convert_with(f64::from));

    if opts.verbose {
        eprintln!("image loaded from \"{}\".\ndithering...", input.display())
    }
    let quantize = create_quantize_n_bits_func(opts.bit_depth)?;

    let output_img = match &opts.color_mode {
        color::Mode::Palette { .. } if opts.bit_depth > 1 => {
            return Err(Error::CustomPaletteIncompatibleWithDepth);
        }

        color::Mode::Color => opts
            .ditherer
            .dither(img, RGB::map_across(quantize))
            .convert_with(|rgb| rgb.convert_with(clamp_f64_to_u8)),

        color::Mode::Palette { palette: p, .. } => opts
            .ditherer
            .dither(img, color::palette::quantize(p))
            .convert_with(|rgb| rgb.convert_with(clamp_f64_to_u8)),

        color::Mode::BlackAndWhite => {
            let bw_img = img.convert_with(|rgb| rgb.to_chroma_corrected_black_and_white());
            opts.ditherer
                .dither(bw_img, quantize)
                .convert_with(RGB::from_chroma_corrected_black_and_white)
        }

        color::Mode::SingleColor(color) => {
            if opts.verbose {
                eprintln!("single_color mode: {:x}", color)
            }

            let bw_img = img.convert_with(|rgb| rgb.to_chroma_corrected_black_and_white());
            let RGB(r, g, b) = *color;
            opts.ditherer
                .dither(bw_img, quantize)
                .convert_with(|x: f64| {
                    RGB(
                        clamp_f64_to_u8(f64::from(r) / 255. * x),
                        clamp_f64_to_u8(f64::from(g) / 255. * x),
                        clamp_f64_to_u8(f64::from(b) / 255. * x),
                    )
                })
        }
    };
    if opts.verbose {
        eprintln!("dithering complete.\nsaving...");
    }
    output_img.save(&output)?;
    if opts.verbose {
        eprintln!("program finished");
    }
    Ok(())
}