printserv/src/dithering.rs

33 lines
917 B
Rust

use image::{
DynamicImage, GrayImage,
imageops::{self, colorops},
};
pub fn auto_brighten(gray: &mut GrayImage) -> () {
let avg = gray.pixels().map(|p| p.0[0] as u32).sum::<u32>() / gray.len() as u32;
if avg < 100 {
colorops::brighten_in_place(gray, 40);
colorops::contrast_in_place(gray, 25.0);
} else if avg > 180 {
colorops::brighten_in_place(gray, -15);
}
}
pub fn dither(gray: &mut GrayImage) -> Vec<u8> {
imageops::dither(gray, &imageops::colorops::BiLevel);
let (w, h) = (gray.width() as usize, gray.height() as usize);
let pitch = (w + 7) >> 3;
let mut bits = vec![0u8; pitch * h];
for y in 0..h {
for x in 0..w {
let byte = y * pitch + (x >> 3);
let bit = 7 - (x & 7);
if gray[(x as u32, y as u32)].0[0] == 0 {
bits[byte] |= 1 << bit;
}
}
}
bits
}