smears/src/main.rs

72 lines
2 KiB
Rust
Raw Normal View History

2021-09-07 10:03:58 -05:00
use image::io::Reader as ImageReader;
2021-09-11 11:13:38 -05:00
use rand::seq::SliceRandom;
2021-09-11 11:14:02 -05:00
use rand::thread_rng;
2021-09-07 10:03:58 -05:00
fn main() -> anyhow::Result<()> {
if let Some(filename) = std::env::args().nth(1) {
println!("{}", filename);
let img = ImageReader::open(filename)?.decode()?;
2021-09-07 10:33:58 -05:00
let rimage = img.to_rgb8();
2021-09-07 10:03:58 -05:00
2021-09-08 10:52:38 -05:00
let all_pixels: Vec<(u32, u32, &image::Rgb<u8>)> = rimage.enumerate_pixels().collect();
let mut iter = 0;
2021-09-08 11:36:40 -05:00
println!("Splitting into chunks...");
2021-09-11 11:13:38 -05:00
let mut chunks = all_pixels.chunks(100_000).collect::<Vec<_>>();
chunks.shuffle(&mut thread_rng());
for chunk in &chunks {
2021-09-08 10:52:38 -05:00
save(rimage.width(), rimage.height(), chunk, iter)?;
2021-09-08 11:36:40 -05:00
println!("Saved image");
2021-09-08 10:52:38 -05:00
iter += 1;
2021-09-07 10:03:58 -05:00
}
} else {
println!("Please provide a valid filename.");
}
2021-09-07 11:14:24 -05:00
Ok(())
}
2021-09-07 11:14:24 -05:00
2021-09-08 11:37:21 -05:00
fn save(
width: u32,
height: u32,
chunk: &[(u32, u32, &image::Rgb<u8>)],
iter: u32,
) -> anyhow::Result<()> {
2021-09-07 15:28:37 -05:00
let white = image::Rgb([255, 255, 255]);
let mut out = image::ImageBuffer::from_pixel(width, height, white);
println!("Created image");
2021-09-08 10:52:38 -05:00
for (x, y, px) in chunk {
out.put_pixel(*x, *y, **px);
2021-09-07 14:16:43 -05:00
}
2021-09-07 11:14:24 -05:00
2021-09-07 15:28:37 -05:00
println!("Applied pixels to new image");
2021-09-11 16:36:21 -05:00
let bytes: Vec<u8> = out.into_raw();
2021-09-11 16:36:21 -05:00
if let Err(e) = std::panic::catch_unwind(|| {
let mut comp = mozjpeg::Compress::new(mozjpeg::ColorSpace::JCS_RGB);
2021-09-11 16:36:21 -05:00
comp.set_size(width as usize, height as usize);
comp.set_mem_dest();
comp.start_compress();
2021-09-11 16:36:21 -05:00
assert!(comp.write_scanlines(&bytes[..]));
2021-09-11 16:36:21 -05:00
comp.finish_compress();
if let Ok(bytes) = comp.data_to_vec() {
println!("Compressed image");
if let Ok(()) = std::fs::write(format!("output/{}.jpg", iter), bytes) {
println!("Wrote new file to disk");
} else {
panic!("Error: could not save the file to disk.");
}
2021-09-11 16:36:21 -05:00
}
}) {
panic!("Error: {:?}", e);
}
2021-09-07 15:28:37 -05:00
2021-09-07 14:16:43 -05:00
Ok(())
2021-09-07 09:26:35 -05:00
}