diff --git a/out.png b/out.png deleted file mode 100644 index e0285af..0000000 Binary files a/out.png and /dev/null differ diff --git a/small.png b/small.png deleted file mode 100644 index df37483..0000000 Binary files a/small.png and /dev/null differ diff --git a/src/dithering.rs b/src/dithering.rs index bc33b6f..4555c42 100644 --- a/src/dithering.rs +++ b/src/dithering.rs @@ -1,7 +1,25 @@ use image::{ - DynamicImage, GrayImage, - imageops::{self, colorops}, + DynamicImage, GrayImage, Luma, + imageops::{self, BiLevel, colorops, colorops::ColorMap, index_colors}, }; + +struct CustomLevel { + threshold: u8, +} + +impl ColorMap for CustomLevel { + type Color = Luma; + + fn index_of(&self, color: &Self::Color) -> usize { + let v = color.0[0]; + if v >= self.threshold { 1 } else { 0 } + } + + fn map_color(&self, color: &mut Self::Color) { + color.0[0] = if color.0[0] >= self.threshold { 255 } else { 0 }; + } +} + pub fn auto_brighten(gray: &mut GrayImage) -> () { let avg = gray.pixels().map(|p| p.0[0] as u32).sum::() / gray.len() as u32; @@ -14,7 +32,8 @@ pub fn auto_brighten(gray: &mut GrayImage) -> () { } pub fn dither(gray: &mut GrayImage) -> Vec { - imageops::dither(gray, &imageops::colorops::BiLevel); + let level = CustomLevel { threshold: 175 }; + let bw: image::ImageBuffer, Vec> = index_colors(&gray, &level); let (w, h) = (gray.width() as usize, gray.height() as usize); let pitch = (w + 7) >> 3; @@ -24,7 +43,7 @@ pub fn dither(gray: &mut GrayImage) -> Vec { 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 { + if bw[(x as u32, y as u32)].0[0] == 0 { bits[byte] |= 1 << bit; } } diff --git a/src/escpos.rs b/src/escpos.rs index ffd49b2..90a2578 100644 --- a/src/escpos.rs +++ b/src/escpos.rs @@ -30,7 +30,7 @@ pub fn escpos_raster( let img = img.resize(w, h, FilterType::Triangle); let mut gray = img.to_luma8(); - auto_brighten(&mut gray); + // auto_brighten(&mut gray); let mono = dither(&mut gray); let (width_px, height_px) = (img.width() as u16, img.height() as u16);