csci5607/assignment-1/src/image.rs

36 lines
851 B
Rust
Raw Normal View History

2023-01-31 20:39:23 +00:00
use std::io::{Result, Write};
/// A 24-bit pixel represented by a red, green, and blue value.
#[derive(Clone, Copy, Default, Debug)]
pub struct Pixel(pub u8, pub u8, pub u8);
/// A representation of an image
pub struct Image {
/// Width in pixels
pub(crate) width: usize,
/// Height in pixels
pub(crate) height: usize,
/// Pixel data in row-major form.
pub(crate) data: Vec<Pixel>,
}
impl Image {
/// Write the image in PPM format to a file.
pub fn write(&self, mut w: impl Write) -> Result<()> {
// Header
let header = format!("P3 {} {} 255\n", self.width, self.height);
w.write_all(header.as_bytes())?;
// Pixel data
for pixel in self.data.iter() {
let Pixel(red, green, blue) = pixel;
let pixel = format!("{red} {green} {blue}\n");
w.write_all(pixel.as_bytes())?;
}
Ok(())
}
}