1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

use std::fs::File;
use std::io::prelude::*;

// Data buffer for image
#[derive(Clone)]
pub struct Ppm {
    pub width: usize,
    pub height: usize,
    pub data: Vec<u8>,
}

impl Ppm {
    pub fn new(width: usize, height: usize) -> Ppm {
        Ppm {
            width,
            height,
            data: vec![0; width * height * 3],
        }
    }

    pub fn read(filename: String) -> Result<Ppm, std::io::Error> {
        // Open the file
        let file = File::open(filename)?;
        let mut reader = std::io::BufReader::new(file);

        let mut line = String::new();
        let _ = reader.read_line(&mut line)?;

        // Check the file type
        if line.len() < 2 || &line[0..2] != "P3" {
            return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid image header - only P3 is supported"));
        }

        // Read dimensions from header
        line.clear();
        while line.is_empty() {
            let _ = reader.read_line(&mut line)?;
        }
        let dimensions = line.split_whitespace().collect::<Vec<&str>>();
        if dimensions.len() < 2 {
            return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid image dimensions"));
        }
        let width: usize = dimensions[0].parse().unwrap_or(0);
        let height: usize = dimensions[1].parse().unwrap_or(0);
        if width == 0 || height == 0 {
            return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid image dimensions"));
        }

        // Read max field value
        line.clear();
        while line.is_empty() {
            let _ = reader.read_line(&mut line)?;
        }
        if line.len() < 3 || &line[0..3] != "255" {
            return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid pixel type, only '255' is supported"));
        }

        let mut ppm = Ppm::new(width, height);

        // Now load the image data
        let mut row : usize = 0;
        loop {
            line.clear();
            let len = reader.read_line(&mut line)?;
            if len == 0 { break; }

            let bytes = line.split_whitespace().collect::<Vec<&str>>();
            let mut index : usize = 0;
            for byte in bytes {
                ppm.data[(row * ppm.width * 3) + index] = byte.parse().unwrap_or(0);
                index += 1;
            }

            row += 1;
        }

        Ok(ppm)
    }

    pub fn write(&self, filename: String) -> std::io::Result<()> {
        let mut file = File::create(filename)?;

        // Colours are ascii
        write!(&mut file, "P3\n")?;
        // Columns, Rows
        write!(&mut file, "{} {}\n", self.width, self.height)?;
        // Maximum value of a colour
        write!(&mut file, "255\n")?;

        for y in 0..self.height {
            for x in 0..self.width {
                let offset = (y * self.width * 3) + x * 3;
                write!(&mut file, "{} {} {} ", 
                        self.data[offset + 0],
                        self.data[offset + 1],
                        self.data[offset + 2]
                        )?;
            }
            write!(&mut file, "\n")?;
        }

        Ok(())
    }

    pub fn set_pixel(&mut self, x: usize, y: usize, r: u8, g: u8, b: u8) {
        let offset = (y * self.width * 3) + x * 3;
        self.data[offset + 0] = r;
        self.data[offset + 1] = g;
        self.data[offset + 2] = b;
    }

    pub fn get_pixel(&self, x: usize, y: usize) -> (u8, u8, u8) {
        let offset = (y * self.width * 3) + x * 3;
        (
            self.data[offset + 0],
            self.data[offset + 1],
            self.data[offset + 2],
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn round_trip() {
        // Make an image
        let width = 10;
        let height = 5;
        let mut orig = Ppm::new(width, height);
        for y in 0..height {
            for x in 0..width {
                orig.set_pixel(x, y, x as u8, y as u8, 0x22);
            }
        }

        // Save it
        let filename = "/tmp/test.ppm";
        orig.write(String::from(filename)).unwrap();
        
        // Load it
        let read_back = Ppm::read(String::from(filename)).unwrap();

        // And verify
        assert_eq!(read_back.width, width);
        assert_eq!(read_back.height, height);
        assert_eq!(read_back.data, orig.data);

        for y in 0..height {
            for x in 0..width {
                let (r,g,b) = read_back.get_pixel(x, y);
                assert_eq!(r, x as u8);
                assert_eq!(g, y as u8);
                assert_eq!(b, 0x22);
            }
        }
    }
}