use std::{fs::File, io::{Error, Write, BufWriter, ErrorKind}}; use image::ImageOutputFormat; pub trait Output { fn write(filename: &str, pixels: &Vec, width: usize, height: usize) -> Result<(), Error>; } pub struct P3 {} impl Output for P3 { fn write(filename: &str, pixels: &Vec, width: usize, height: usize) -> Result<(), Error> { let mut file = File::create(filename)?; file.write(format!("P3\n{} {}\n255\n", width, height).as_bytes())?; let lines: Result, Error> = pixels .chunks(3) .map(|chunk| format!("{} {} {}\n", chunk[0], chunk[1], chunk[2])) .map(|line| file.write(line.as_bytes())) .collect(); lines.map(|_l|()) } } pub struct PNG {} impl Output for PNG { fn write(filename: &str, pixels: &Vec, width: usize, height: usize) -> Result<(), Error> { let file = File::create(filename)?; let ref mut writer = BufWriter::new(file); image::write_buffer_with_format( writer, pixels, width as u32, height as u32, image::ColorType::Rgb8, ImageOutputFormat::Png) .map_err(|e| Error::new(ErrorKind::Other, e)) } }