1use std::fmt;
4
5#[derive(Clone, PartialEq, Eq)]
7pub struct RgbaImage {
8 width: usize,
9 height: usize,
10 data: Vec<u8>,
11}
12
13impl fmt::Debug for RgbaImage {
14 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 f.debug_struct("RgbaImage")
16 .field("width", &self.width)
17 .field("height", &self.height)
18 .finish_non_exhaustive()
19 }
20}
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct ImageSizeError {
25 pub expected: usize,
27 pub actual: usize,
29}
30
31impl fmt::Display for ImageSizeError {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 write!(
34 f,
35 "RGBA image needs {} bytes, got {}",
36 self.expected, self.actual
37 )
38 }
39}
40
41impl std::error::Error for ImageSizeError {}
42
43impl RgbaImage {
44 pub fn new(width: usize, height: usize, data: Vec<u8>) -> Result<Self, ImageSizeError> {
46 let expected = width * height * 4;
47 if data.len() == expected {
48 Ok(Self {
49 width,
50 height,
51 data,
52 })
53 } else {
54 Err(ImageSizeError {
55 expected,
56 actual: data.len(),
57 })
58 }
59 }
60
61 pub fn transparent(width: usize, height: usize) -> Self {
63 Self {
64 width,
65 height,
66 data: vec![0; width * height * 4],
67 }
68 }
69
70 pub const fn width(&self) -> usize {
72 self.width
73 }
74
75 pub const fn height(&self) -> usize {
77 self.height
78 }
79
80 pub fn data(&self) -> &[u8] {
82 &self.data
83 }
84
85 pub fn data_mut(&mut self) -> &mut [u8] {
87 &mut self.data
88 }
89
90 pub fn into_data(self) -> Vec<u8> {
92 self.data
93 }
94
95 pub fn opaque_bounds(&self) -> Option<(usize, usize, usize, usize)> {
100 let alpha = |x: usize, y: usize| self.data[(y * self.width + x) * 4 + 3];
101 let rows: Vec<usize> = (0..self.height)
102 .filter(|&y| (0..self.width).any(|x| alpha(x, y) != 0))
103 .collect();
104 let columns: Vec<usize> = (0..self.width)
105 .filter(|&x| (0..self.height).any(|y| alpha(x, y) != 0))
106 .collect();
107 Some((
108 *columns.first()?,
109 *rows.first()?,
110 *columns.last()? + 1,
111 *rows.last()? + 1,
112 ))
113 }
114
115 pub(crate) fn crop(&self, (left, top, right, bottom): (usize, usize, usize, usize)) -> Self {
118 let data: Vec<u8> = (top..bottom)
119 .flat_map(|y| {
120 self.data[(y * self.width + left) * 4..(y * self.width + right) * 4].iter()
121 })
122 .copied()
123 .collect();
124 Self::new(right - left, bottom - top, data).expect("the crop holds its own pixels")
125 }
126
127 pub fn pixel(&self, x: usize, y: usize) -> Option<[u8; 4]> {
129 (x < self.width && y < self.height).then(|| {
130 let i = (y * self.width + x) * 4;
131 [
132 self.data[i],
133 self.data[i + 1],
134 self.data[i + 2],
135 self.data[i + 3],
136 ]
137 })
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144
145 #[test]
146 fn crops_to_the_opaque_pixels() {
147 let mut data = vec![0; 4 * 3 * 4];
148 data[(4 + 2) * 4 + 3] = 255;
149 let image = RgbaImage::new(4, 3, data).unwrap();
150 assert_eq!(image.opaque_bounds(), Some((2, 1, 3, 2)));
151 assert_eq!(image.crop((2, 1, 3, 2)).data(), &[0, 0, 0, 255]);
152 assert_eq!(RgbaImage::transparent(2, 2).opaque_bounds(), None);
153 }
154
155 #[test]
156 fn size_validation_and_access() {
157 assert_eq!(
158 RgbaImage::new(2, 2, vec![0; 15]),
159 Err(ImageSizeError {
160 expected: 16,
161 actual: 15
162 })
163 );
164 let mut img = RgbaImage::transparent(2, 1);
165 img.data_mut()[4..8].copy_from_slice(&[1, 2, 3, 4]);
166 assert_eq!(img.pixel(1, 0), Some([1, 2, 3, 4]));
167 assert_eq!(img.pixel(2, 0), None);
168 }
169}