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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use crate::*;

use riddle_common::{Color, ColorElementConversion};
use riddle_math::*;

use futures::{AsyncRead, AsyncReadExt};
use std::io::{BufReader, Cursor, Read};

/// A representation of an image stored in main memory. The image is stored
/// as RGBA32.
#[derive(Clone)]
pub struct Image {
    img: ::image::RgbaImage,
}

impl Image {
    /// Load an image from a `Read` instance which emits image file data in the
    /// specified format.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*; fn main() -> Result<(), ImageError> {
    /// let png_bytes = include_bytes!("../../example_assets/image.png");
    /// let png_img = Image::load(&png_bytes[..], ImageFormat::Png)?;
    /// # Ok(()) }
    /// ```
    pub fn load<R: Read>(mut r: R, format: ImageFormat) -> Result<Self> {
        let mut buf = vec![];
        r.read_to_end(&mut buf)?;
        Self::from_bytes(&buf, format)
    }

    /// Load an image from a `AsyncRead` instance which emits image file data in the
    /// specified format.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*; fn main() -> Result<(), ImageError> { futures::executor::block_on(async_main()) }
    /// # async fn async_main() -> Result<(), ImageError> {
    /// let png_bytes = include_bytes!("../../example_assets/image.png");
    /// let png_img = Image::load_async(&png_bytes[..], ImageFormat::Png).await?;
    /// # Ok(()) }
    /// ```
    pub async fn load_async<R>(mut data: R, format: ImageFormat) -> Result<Self>
    where
        R: AsyncRead + Unpin,
    {
        let mut buf = vec![];
        data.read_to_end(&mut buf).await?;
        Self::from_bytes(&buf, format)
    }

    /// Load an image from a byte slice in the specified format.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*; fn main() -> Result<(), ImageError> {
    /// let png_bytes = include_bytes!("../../example_assets/image.png");
    /// let png_img = Image::from_bytes(&png_bytes[..], ImageFormat::Png)?;
    /// # Ok(()) }
    /// ```
    pub fn from_bytes(bytes: &[u8], format: ImageFormat) -> Result<Self> {
        let buf_reader = BufReader::new(Cursor::new(bytes));
        let img = match format {
            ImageFormat::Png => {
                ::image::DynamicImage::from_decoder(::image::png::PngDecoder::new(buf_reader)?)?
            }
            ImageFormat::Bmp => {
                ::image::DynamicImage::from_decoder(::image::bmp::BmpDecoder::new(buf_reader)?)?
            }
            ImageFormat::Jpeg => {
                ::image::DynamicImage::from_decoder(::image::jpeg::JpegDecoder::new(buf_reader)?)?
            }
        };
        Ok(Image {
            img: img.into_rgba(),
        })
    }

    /// Create a new image with the given dimensions, all pixels are initialized
    /// to 0x00000000.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// // Create a single pixel image
    /// let img = Image::new(1,1);
    /// ```
    pub fn new(width: u32, height: u32) -> Self {
        let img =
            ::image::RgbaImage::from_raw(width, height, vec![0u8; (width * height * 4) as usize])
                .unwrap();
        Image { img }
    }

    /// Get the color of the pixel at the given coordinates
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(Color::rgba(0,0,0,0), img.get_pixel(0, 0));
    /// ```
    pub fn get_pixel(&self, x: u32, y: u32) -> Color<u8> {
        let c: ::image::Rgba<u8> = *self.img.get_pixel(x, y);
        Color::rgba(c[0], c[1], c[2], c[3])
    }

    /// Set the color of the pixel at the given coordinates
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let mut img = Image::new(1,1);
    /// img.set_pixel(0, 0, Color::rgba(1.0, 0.0, 0.0, 1.0));
    /// assert_eq!(Color::rgba(255,0,0,255), img.get_pixel(0, 0));
    /// ```
    pub fn set_pixel<C: ColorElementConversion<Color<u8>>>(&mut self, x: u32, y: u32, color: C) {
        let color: Color<u8> = color.convert();
        let color: [u8; 4] = color.into();
        self.img.put_pixel(x, y, color.into());
    }

    /// Borrow the bytes representing the entire image, encoded as RGBA8
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(0x00u8, img.as_rgba8()[0]);
    /// ```
    pub fn as_rgba8(&self) -> &[u8] {
        self.img.as_ref()
    }

    /// Mutably borrow the bytes representing the entire image, encoded as RGBA8
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let mut img = Image::new(1,1);
    /// let bytes = img.as_rgba8_mut();
    /// bytes[0] = 0xFF;
    /// assert_eq!(Color::rgba(255, 0, 0, 0), img.get_pixel(0,0));
    /// ```
    pub fn as_rgba8_mut(&mut self) -> &mut [u8] {
        self.img.as_mut()
    }

    /// Get the byte count of the entire image encoded as RGBA8
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(4, img.byte_count());
    /// ```
    pub fn byte_count(&self) -> usize {
        self.img.as_ref().len()
    }

    /// Width of the image in pixels
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(1, img.width());
    /// ```
    pub fn width(&self) -> u32 {
        self.img.width()
    }

    /// Height of the image in pixels
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(1, img.height());
    /// ```
    pub fn height(&self) -> u32 {
        self.img.height()
    }

    /// Dimension of the image in pixels
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*; use riddle_math::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(Vector2::new(1, 1), img.dimensions());
    /// ```
    pub fn dimensions(&self) -> Vector2<u32> {
        let (w, h) = self.img.dimensions();
        Vector2 { x: w, y: h }
    }

    /// Get the bounding rect for the image, located at (0,0) and having size
    /// equal to the image's dimensions.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*; use riddle_math::*;
    /// let img = Image::new(1,1);
    /// assert_eq!(Rect::new(Vector2::new(0, 0), Vector2::new(1, 1)), img.rect());
    /// ```
    pub fn rect(&self) -> Rect<u32> {
        Rect {
            location: Vector2 { x: 0, y: 0 },
            dimensions: self.dimensions(),
        }
    }

    /// Blit another image on to self. The location is the relative offset of the (0,0) pixel of the
    /// source image relative to self's (0,0) pixel.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_image::*; use riddle_math::*;
    /// let mut source = Image::new(1,1);
    /// source.set_pixel(0, 0, Color::<u8>::RED);
    ///
    /// let mut dest = Image::new(2,1);
    /// dest.blit(&source, Vector2::new(1, 0));
    ///
    /// assert_eq!(Color::ZERO, dest.get_pixel(0,0));
    /// assert_eq!(Color::RED, dest.get_pixel(1, 0));
    /// ```
    pub fn blit(&mut self, source: &Image, location: Vector2<i32>) {
        if let Some((dest_rect, src_rect)) =
            Rect::intersect_relative_to_both(self.dimensions(), source.dimensions(), location)
        {
            let mut dest_view = self.create_view_mut(dest_rect.clone().convert());
            let src_view = source.create_view(src_rect.convert());

            for row in 0..(dest_rect.dimensions.y as u32) {
                let dest = dest_view.get_row_rgba8_mut(row);
                let src = src_view.get_row_rgba8(row);

                dest.clone_from_slice(src);
            }
        }
    }

    pub(crate) fn create_view(&self, rect: Rect<u32>) -> ImageView {
        ImageView::new(self, rect)
    }

    pub(crate) fn create_view_mut(&mut self, rect: Rect<u32>) -> ImageViewMut {
        ImageViewMut::new(self, rect)
    }
}

impl image_ext::ImageImageExt for Image {
    fn image_rgbaimage(&self) -> &::image::RgbaImage {
        &self.img
    }
}

/// The set of support image file formats which [`Image`] can load
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum ImageFormat {
    Png,
    Bmp,
    Jpeg,
}