Skip to main content

pltrs_codec/png/
image.rs

1//! Borrowed pixel data handed to the encoder.
2
3use super::error::EncodeError;
4use super::header::valid_dimensions;
5use super::types::{BitDepth, ColorType, PixelFormat};
6
7/// A borrowed, validated view of pixels to encode.
8///
9/// Rows run top to bottom with no padding between them. 16-bit samples are
10/// big-endian byte pairs (PNG's own order); 1-, 2- and 4-bit grey samples are
11/// packed most significant bits first, each row starting on a fresh byte.
12///
13/// ```
14/// use pltrs_codec::png::{BitDepth, ColorType, ImageRef};
15///
16/// let pixels = [0u8; 3 * 2 * 4];
17/// let image = ImageRef::rgba8(3, 2, &pixels)?;
18/// assert_eq!(image.row_bytes(), 12);
19///
20/// // Two 16-bit grey pixels: 0x0102 and 0xFFFF.
21/// let image = ImageRef::new(2, 1, ColorType::Gray, BitDepth::Sixteen, &[1, 2, 0xFF, 0xFF])?;
22/// assert!(ImageRef::rgba8(3, 3, &pixels).is_err());
23/// # Ok::<(), pltrs_codec::png::EncodeError>(())
24/// ```
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct ImageRef<'a> {
27    width: u32,
28    height: u32,
29    format: PixelFormat,
30    data: &'a [u8],
31}
32
33impl<'a> ImageRef<'a> {
34    /// Wraps `data` as a `width` × `height` image in the given format.
35    ///
36    /// The encoder supports grey at every bit depth and grey + alpha, RGB and
37    /// RGBA at 8 or 16 bits; indexed images are not supported.
38    pub fn new(
39        width: u32,
40        height: u32,
41        color: ColorType,
42        bit_depth: BitDepth,
43        data: &'a [u8],
44    ) -> Result<Self, EncodeError> {
45        if !valid_dimensions(width, height) {
46            return Err(EncodeError::InvalidDimensions { width, height });
47        }
48        let format = PixelFormat::new(color, bit_depth)
49            .filter(|_| color != ColorType::Indexed)
50            .ok_or(EncodeError::UnsupportedFormat { color, bit_depth })?;
51        let expected = format
52            .image_bytes(width, height)
53            .ok_or(EncodeError::ImageTooLarge)?;
54        if data.len() != expected {
55            return Err(EncodeError::DataLengthMismatch {
56                expected,
57                actual: data.len(),
58            });
59        }
60        Ok(Self {
61            width,
62            height,
63            format,
64            data,
65        })
66    }
67
68    /// Wraps 8-bit RGBA pixels (4 bytes per pixel), the format of rendered
69    /// figures.
70    pub fn rgba8(width: u32, height: u32, data: &'a [u8]) -> Result<Self, EncodeError> {
71        Self::new(width, height, ColorType::Rgba, BitDepth::Eight, data)
72    }
73
74    /// Wraps 8-bit RGB pixels (3 bytes per pixel).
75    pub fn rgb8(width: u32, height: u32, data: &'a [u8]) -> Result<Self, EncodeError> {
76        Self::new(width, height, ColorType::Rgb, BitDepth::Eight, data)
77    }
78
79    /// Width in pixels.
80    pub const fn width(&self) -> u32 {
81        self.width
82    }
83
84    /// Height in pixels.
85    pub const fn height(&self) -> u32 {
86        self.height
87    }
88
89    /// Colour type of the pixels.
90    pub const fn color_type(&self) -> ColorType {
91        self.format.color
92    }
93
94    /// Bits per sample.
95    pub const fn bit_depth(&self) -> BitDepth {
96        self.format.depth
97    }
98
99    /// The pixel bytes.
100    pub const fn data(&self) -> &'a [u8] {
101        self.data
102    }
103
104    /// Bytes per row.
105    pub fn row_bytes(&self) -> usize {
106        self.data.len() / self.height as usize
107    }
108
109    pub(crate) const fn format(&self) -> PixelFormat {
110        self.format
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn validates_dimensions_format_and_length() {
120        assert_eq!(
121            ImageRef::rgba8(0, 1, &[]),
122            Err(EncodeError::InvalidDimensions {
123                width: 0,
124                height: 1
125            })
126        );
127        assert_eq!(
128            ImageRef::rgba8(1, 1 << 31, &[]),
129            Err(EncodeError::InvalidDimensions {
130                width: 1,
131                height: 1 << 31
132            })
133        );
134        assert_eq!(
135            ImageRef::new(1, 1, ColorType::Indexed, BitDepth::Eight, &[0]),
136            Err(EncodeError::UnsupportedFormat {
137                color: ColorType::Indexed,
138                bit_depth: BitDepth::Eight
139            })
140        );
141        assert_eq!(
142            ImageRef::new(1, 1, ColorType::Rgb, BitDepth::Four, &[0, 0]),
143            Err(EncodeError::UnsupportedFormat {
144                color: ColorType::Rgb,
145                bit_depth: BitDepth::Four
146            })
147        );
148        assert_eq!(
149            ImageRef::rgb8(2, 2, &[0; 11]),
150            Err(EncodeError::DataLengthMismatch {
151                expected: 12,
152                actual: 11
153            })
154        );
155    }
156
157    #[test]
158    fn packed_grey_rows_are_padded_to_bytes() {
159        let image = ImageRef::new(9, 2, ColorType::Gray, BitDepth::One, &[0; 4]).unwrap();
160        assert_eq!(image.row_bytes(), 2);
161        assert_eq!((image.width(), image.height()), (9, 2));
162        assert_eq!(
163            (image.color_type(), image.bit_depth()),
164            (ColorType::Gray, BitDepth::One)
165        );
166        assert_eq!(image.data().len(), 4);
167    }
168}