rayimg/image_write/
p3_image_writer.rs

1use super::ImageWrite;
2
3use std::io::Write;
4
5/// Writes bytes (i.e. `[u8; 3]`) to *.ppm files.
6pub struct P3ImageWriter<W> {
7    bounds: (usize, usize),
8    w: W
9}
10
11impl<W: Write> P3ImageWriter<W> {
12    /// Creates new P3ImageWriter.
13    /// ```
14    /// # use rayimg::{P3ImageWriter, ImageWrite, RGB};
15    /// # use std::io::Write;
16    /// let mut buf = Vec::new();
17    /// let mut image_writer = P3ImageWriter::new((640, 480), &mut buf);
18    /// image_writer.write_image_data(&[[0, 128, 255]]);
19    /// assert_eq!(String::from_utf8(buf).unwrap(), String::from("P3\n640 480\n255\n0 128 255\n"));
20    /// ```
21    pub fn new(bounds: (usize, usize), w: W) -> Self {
22        let mut writer = Self {
23            bounds,
24            w
25        };
26
27        writer.write_header();
28        writer
29    }
30
31    fn write_header(&mut self) {
32        write!(self.w, "P3\n{} {}\n255\n", self.bounds.0, self.bounds.1).unwrap();
33    }
34}
35
36impl<W: Write> ImageWrite for P3ImageWriter<W> {
37    type Color = [u8; 3];
38
39    fn write_image_data(&mut self, data: &[Self::Color]) {
40        for color in data {
41            write!(self.w, "{} {} {}\n", color[0], color[1], color[2]).unwrap();
42        }
43    }
44
45    fn bounds(&self) -> (usize, usize) {
46        self.bounds
47    }
48}