csci5607/assignment-0/src/image.rs

35 lines
814 B
Rust
Raw Normal View History

2023-01-21 08:03:11 +00:00
use std::io::{Result, Write};
2023-01-21 08:55:19 +00:00
/// A 24-bit pixel represented by a red, green, and blue value.
2023-01-21 08:03:11 +00:00
pub struct Pixel(pub u8, pub u8, pub u8);
2023-01-21 08:55:19 +00:00
/// A representation of an image
pub struct Image {
/// Width in pixels
2023-01-21 08:22:22 +00:00
pub(crate) width: usize,
2023-01-21 08:55:19 +00:00
/// Height in pixels
2023-01-21 08:22:22 +00:00
pub(crate) height: usize,
2023-01-21 08:55:19 +00:00
/// Pixel data in row-major form.
2023-01-21 08:22:22 +00:00
pub(crate) data: Vec<Pixel>,
2023-01-21 08:03:11 +00:00
}
2023-01-21 08:55:19 +00:00
impl Image {
/// Write the image in PPM format to a file.
2023-01-21 08:22:22 +00:00
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())?;
2023-01-21 08:03:11 +00:00
2023-01-21 08:22:22 +00:00
// 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())?;
2023-01-21 08:03:11 +00:00
}
2023-01-21 08:22:22 +00:00
Ok(())
}
2023-01-21 08:03:11 +00:00
}