2022-07-03 17:24:27 +00:00
|
|
|
use std::{fs::File, io::{Error, Write, BufWriter, ErrorKind}};
|
|
|
|
|
|
|
|
use image::ImageOutputFormat;
|
2022-07-02 13:42:04 +00:00
|
|
|
|
|
|
|
pub trait Output {
|
2022-07-03 17:24:27 +00:00
|
|
|
fn write(filename: &str, pixels: &Vec<u8>, width: usize, height: usize) -> Result<(), Error>;
|
2022-07-02 13:42:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct P3 {}
|
|
|
|
impl Output for P3 {
|
2022-07-03 17:24:27 +00:00
|
|
|
fn write(filename: &str, pixels: &Vec<u8>, width: usize, height: usize) -> Result<(), Error> {
|
2022-07-02 13:42:04 +00:00
|
|
|
let mut file = File::create(filename)?;
|
|
|
|
file.write(format!("P3\n{} {}\n255\n", width, height).as_bytes())?;
|
|
|
|
let lines: Result<Vec<usize>, Error> = pixels
|
|
|
|
.chunks(3)
|
|
|
|
.map(|chunk| format!("{} {} {}\n", chunk[0], chunk[1], chunk[2]))
|
|
|
|
.map(|line| file.write(line.as_bytes()))
|
|
|
|
.collect();
|
2022-07-03 17:24:27 +00:00
|
|
|
lines.map(|_l|())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct PNG {}
|
|
|
|
impl Output for PNG {
|
|
|
|
fn write(filename: &str, pixels: &Vec<u8>, 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))
|
2022-07-02 13:42:04 +00:00
|
|
|
}
|
|
|
|
}
|