Skip to main content

aseprite/
image_conv.rs

1use image::RgbaImage;
2
3use crate::error::AsepriteError;
4use crate::types::Pixels;
5
6/// Converts an [`image::RgbaImage`] into [`Pixels`] (zero-copy, takes ownership of the buffer).
7impl From<RgbaImage> for Pixels {
8    fn from(img: RgbaImage) -> Self {
9        let width = img.width() as u16;
10        let height = img.height() as u16;
11        Self {
12            data: img.into_raw(),
13            width,
14            height,
15        }
16    }
17}
18
19/// Converts [`Pixels`] into an [`image::RgbaImage`].
20///
21/// Returns [`AsepriteError::PixelSizeMismatch`] if the buffer size is invalid.
22impl TryFrom<Pixels> for RgbaImage {
23    type Error = AsepriteError;
24
25    fn try_from(pixels: Pixels) -> Result<Self, Self::Error> {
26        RgbaImage::from_raw(pixels.width as u32, pixels.height as u32, pixels.data).ok_or(
27            AsepriteError::PixelSizeMismatch {
28                expected: pixels.width as usize * pixels.height as usize * 4,
29                actual: 0,
30            },
31        )
32    }
33}