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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::{
    pixel::{self, ColorType, Pixel},
    PixEngineErr, PixEngineResult,
};
use png;
use std::{
    cell::RefCell,
    ffi::OsStr,
    io::{BufReader, BufWriter},
    rc::Rc,
};

pub type ImageRef = Rc<RefCell<Image>>;

#[derive(Clone)]
pub struct Image {
    width: u32,
    height: u32,
    channels: u8,
    color_type: ColorType,
    data: Vec<u8>,
}

impl Image {
    /// Creates a new image with given size
    pub fn new(width: u32, height: u32) -> Self {
        Self::rgba(width, height)
    }

    pub fn new_ref(width: u32, height: u32) -> ImageRef {
        Rc::new(RefCell::new(Self::new(width, height)))
    }

    pub fn ref_from(image: Image) -> ImageRef {
        Rc::new(RefCell::new(image))
    }

    pub fn rgb(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            channels: 3,
            color_type: ColorType::Rgb,
            data: vec![0; 3 * (width * height) as usize],
        }
    }

    pub fn rgb_ref(width: u32, height: u32) -> ImageRef {
        Self::ref_from(Self::rgb(width, height))
    }

    pub fn rgba(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            channels: 4,
            color_type: ColorType::Rgba,
            data: vec![0; 4 * (width * height) as usize],
        }
    }

    pub fn rgba_ref(width: u32, height: u32) -> ImageRef {
        Self::ref_from(Self::rgba(width, height))
    }

    /// Creates a new image from an array of bytes
    pub fn from_bytes(width: u32, height: u32, bytes: &[u8]) -> PixEngineResult<Self> {
        if bytes.len() != (4 * width * height) as usize {
            Err(PixEngineErr::new(
                "width/height does not match bytes length",
            ))
        } else {
            Ok(Self {
                width,
                height,
                channels: 4,
                color_type: ColorType::Rgba,
                data: bytes.to_vec(),
            })
        }
    }

    /// Gets the pixel at the given (x, y) coords
    pub fn get_pixel(&self, x: u32, y: u32) -> Pixel {
        if x < self.width && y < self.height {
            let idx = self.channels as usize * (y * self.width + x) as usize;
            Pixel([
                self.data[idx],
                self.data[idx + 1],
                self.data[idx + 2],
                if self.channels == 3 {
                    255
                } else {
                    self.data[idx + 3]
                },
            ])
        } else {
            pixel::TRANSPARENT
        }
    }

    /// Sets the pixel at the given (x, y) coords
    pub fn put_pixel(&mut self, x: u32, y: u32, p: Pixel) {
        if x < self.width && y < self.height {
            let idx = self.channels as usize * (y * self.width + x) as usize;
            for i in 0..self.channels as usize {
                self.data[idx + i] = p[i];
            }
        }
    }

    /// ColorType of the image
    pub fn color_type(&self) -> ColorType {
        self.color_type
    }

    /// Width of the image
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Height of the image
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Returns a reference to the pixels within the image
    pub fn bytes(&self) -> &Vec<u8> {
        &self.data
    }

    /// Returns a mutable reference to the pixels within the image
    pub fn bytes_mut(&mut self) -> &mut Vec<u8> {
        &mut self.data
    }

    /// Create a new image from a PNG file
    /// Only 8-bit RGBA formats are supported currently
    pub fn from_file(file: &str) -> PixEngineResult<Self> {
        use std::path::PathBuf;
        let path = PathBuf::from(file);
        if path.extension() != Some(OsStr::new("png")) {
            return Err(PixEngineErr::new("invalid png file"));
        }

        let png_file = BufReader::new(std::fs::File::open(&path)?);
        let png = png::Decoder::new(png_file);
        let (info, mut reader) = png.read_info()?;

        assert_eq!(
            info.color_type,
            png::ColorType::RGBA,
            "Only RGBA formats supported right now."
        );
        assert_eq!(
            info.bit_depth,
            png::BitDepth::Eight,
            "Only 8-bit formats supported right now."
        );

        let mut data = vec![0; info.buffer_size()];
        reader.next_frame(&mut data).unwrap();

        Image::from_bytes(info.width, info.height, &data)
    }

    /// Saves a image out to a png file
    pub fn save_to_file(&mut self, file: &str) -> PixEngineResult<()> {
        use std::path::PathBuf;
        let path = PathBuf::from(file);
        let png_file = BufWriter::new(std::fs::File::create(&path)?);
        let mut png = png::Encoder::new(png_file, self.width, self.height);
        png.set_color(png::ColorType::RGBA);
        let mut writer = png.write_header()?;
        writer.write_image_data(self.bytes())?;
        Ok(())
    }
}

impl From<png::DecodingError> for PixEngineErr {
    fn from(err: png::DecodingError) -> Self {
        Self::new(err)
    }
}
impl From<png::EncodingError> for PixEngineErr {
    fn from(err: png::EncodingError) -> Self {
        Self::new(err)
    }
}