sunday_slate/media/
process.rs1use image::{DynamicImage, ImageFormat, ImageReader, Limits, imageops::FilterType};
4use std::io::Cursor;
5
6const MAX_DECODE_DIMENSION: u32 = 8192;
9const MAX_DECODE_ALLOC_BYTES: u64 = 96 * 1024 * 1024;
13const AVATAR_MAX_AXIS: u32 = 256;
14
15#[derive(Debug, thiserror::Error)]
16pub enum ProcessError {
17 #[error("Unsupported image format. Upload a PNG, JPEG, or WebP.")]
18 UnsupportedFormat,
19 #[error("That file could not be read as an image.")]
20 Decode,
21 #[error("Failed to process the image.")]
22 Encode,
23}
24
25#[derive(Debug)]
26pub struct ProcessedImage {
27 pub png: Vec<u8>,
28 pub width: u32,
29 pub height: u32,
30}
31
32fn decode(bytes: &[u8]) -> Result<DynamicImage, ProcessError> {
33 let format = match image::guess_format(bytes) {
34 Ok(format @ (ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP)) => format,
35 _ => return Err(ProcessError::UnsupportedFormat),
36 };
37
38 let mut limits = Limits::default();
39 limits.max_image_width = Some(MAX_DECODE_DIMENSION);
40 limits.max_image_height = Some(MAX_DECODE_DIMENSION);
41 limits.max_alloc = Some(MAX_DECODE_ALLOC_BYTES);
42
43 let mut reader = ImageReader::new(Cursor::new(bytes));
44 reader.set_format(format);
45 reader.limits(limits);
46 reader.decode().map_err(|_| ProcessError::Decode)
47}
48
49fn encode_png(image: &DynamicImage) -> Result<Vec<u8>, ProcessError> {
50 let mut buf = Cursor::new(Vec::new());
51 image
52 .write_to(&mut buf, ImageFormat::Png)
53 .map_err(|_| ProcessError::Encode)?;
54 Ok(buf.into_inner())
55}
56
57pub fn process_logo(bytes: &[u8]) -> Result<Vec<u8>, ProcessError> {
60 let img = decode(bytes)?;
61 let (w, h) = (img.width(), img.height());
62 let side = w.min(h);
63 let x = (w - side) / 2;
64 let y = (h - side) / 2;
65 let square = img.crop_imm(x, y, side, side);
66 let resized = square.resize_exact(256, 256, FilterType::Lanczos3);
67 encode_png(&resized)
68}
69
70pub fn process_avatar(bytes: &[u8]) -> Result<ProcessedImage, ProcessError> {
71 let img = decode(bytes)?;
72 let (w, h) = (img.width(), img.height());
73 let processed = if w.max(h) > AVATAR_MAX_AXIS {
74 let max_axis = w.max(h);
75 let width = ((u64::from(w) * u64::from(AVATAR_MAX_AXIS) + u64::from(max_axis) / 2)
76 / u64::from(max_axis)) as u32;
77 let height = ((u64::from(h) * u64::from(AVATAR_MAX_AXIS) + u64::from(max_axis) / 2)
78 / u64::from(max_axis)) as u32;
79 img.resize_exact(width.max(1), height.max(1), FilterType::Lanczos3)
80 } else {
81 img
82 };
83 let width = processed.width();
84 let height = processed.height();
85 Ok(ProcessedImage {
86 png: encode_png(&processed)?,
87 width,
88 height,
89 })
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95 use image::{DynamicImage, ImageFormat, RgbImage};
96 use std::io::Cursor;
97
98 fn encode(w: u32, h: u32, format: ImageFormat) -> Vec<u8> {
99 let img = DynamicImage::ImageRgb8(RgbImage::new(w, h));
100 let mut buf = Cursor::new(Vec::new());
101 img.write_to(&mut buf, format).expect("encode");
102 buf.into_inner()
103 }
104
105 fn decode_dims(bytes: &[u8]) -> (u32, u32) {
106 let img = image::load_from_memory(bytes).expect("decode output");
107 (img.width(), img.height())
108 }
109
110 #[test]
111 fn resizes_non_square_png_to_256_square() {
112 let input = encode(400, 200, ImageFormat::Png);
113 let out = process_logo(&input).expect("process");
114 assert_eq!(image::guess_format(&out).unwrap(), ImageFormat::Png);
115 assert_eq!(decode_dims(&out), (256, 256));
116 }
117
118 #[test]
119 fn accepts_jpeg_and_outputs_png() {
120 let input = encode(300, 300, ImageFormat::Jpeg);
121 let out = process_logo(&input).expect("process");
122 assert_eq!(image::guess_format(&out).unwrap(), ImageFormat::Png);
123 assert_eq!(decode_dims(&out), (256, 256));
124 }
125
126 #[test]
127 fn rejects_non_image_bytes() {
128 let err = process_logo(b"this is not an image").unwrap_err();
129 assert!(matches!(
130 err,
131 ProcessError::UnsupportedFormat | ProcessError::Decode
132 ));
133 }
134
135 #[test]
137 fn rejects_images_exceeding_the_decode_dimension_cap() {
138 let input = encode(MAX_DECODE_DIMENSION + 1, 1, ImageFormat::Png);
139 assert!(matches!(process_logo(&input), Err(ProcessError::Decode)));
140 }
141
142 #[test]
143 fn rejects_unsupported_format() {
144 let gif = b"GIF89a\x01\x00\x01\x00\x00\x00\x00;";
147 assert!(matches!(
148 process_logo(gif),
149 Err(ProcessError::UnsupportedFormat)
150 ));
151 }
152 #[test]
153 fn process_avatar_wide_preserves_aspect_ratio() {
154 let processed = process_avatar(&encode(400, 200, ImageFormat::Png)).expect("process");
155 assert_eq!((processed.width, processed.height), (256, 128));
156 assert!(processed.width.max(processed.height) <= 256);
157 }
158
159 #[test]
160 fn process_avatar_tall_preserves_aspect_ratio() {
161 let processed = process_avatar(&encode(200, 400, ImageFormat::Jpeg)).expect("process");
162 assert_eq!((processed.width, processed.height), (128, 256));
163 assert!(processed.width.max(processed.height) <= 256);
164 }
165
166 #[test]
167 fn process_avatar_small_image_keeps_original_dimensions() {
168 let processed = process_avatar(&encode(120, 80, ImageFormat::Png)).expect("process");
169 assert_eq!((processed.width, processed.height), (120, 80));
170 }
171
172 #[test]
173 fn process_avatar_outputs_png() {
174 let processed = process_avatar(&encode(64, 64, ImageFormat::WebP)).expect("process");
175 assert_eq!(
176 image::guess_format(&processed.png).expect("format"),
177 ImageFormat::Png
178 );
179 }
180
181 #[test]
182 fn process_avatar_rejects_unsupported_format() {
183 let err = process_avatar(b"not an image").unwrap_err();
184 assert!(matches!(err, ProcessError::UnsupportedFormat));
185 }
186}