1use image::imageops::FilterType;
8use image::ImageError;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ResizeTarget {
14 Exact { width: u32, height: u32 },
19 Width { width: u32 },
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum EncodedFormat {
34 Avif,
35 Webp,
36 Jpeg,
37}
38
39impl EncodedFormat {
40 pub fn content_type(self) -> &'static str {
41 match self {
42 EncodedFormat::Avif => "image/avif",
43 EncodedFormat::Webp => "image/webp",
44 EncodedFormat::Jpeg => "image/jpeg",
45 }
46 }
47
48 pub fn extension(self) -> &'static str {
49 match self {
50 EncodedFormat::Avif => "avif",
51 EncodedFormat::Webp => "webp",
52 EncodedFormat::Jpeg => "jpg",
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum FormatPreference {
66 Avif,
67 Webp,
68 Jpeg,
69}
70
71#[derive(Debug)]
72pub struct Optimized {
73 pub bytes: Vec<u8>,
74 pub format: EncodedFormat,
75}
76
77#[derive(Debug)]
84pub struct OptimizeResult {
85 pub main: Optimized,
86 pub blur: Option<Vec<u8>>,
87}
88
89#[derive(Debug)]
90pub enum OptimizeError {
91 Decode(ImageError),
92 Encode(String),
93}
94
95impl std::fmt::Display for OptimizeError {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 match self {
98 OptimizeError::Decode(error) => write!(f, "failed to decode source image: {error}"),
99 OptimizeError::Encode(message) => write!(f, "failed to encode image: {message}"),
100 }
101 }
102}
103
104impl std::error::Error for OptimizeError {}
105
106const BLUR_WIDTH: u32 = 16;
113const BLUR_QUALITY: u8 = 30;
114
115pub fn optimize(
124 source: &[u8],
125 target: ResizeTarget,
126 quality: u8,
127 preferred_format: FormatPreference,
128 generate_blur: bool,
129) -> Result<OptimizeResult, OptimizeError> {
130 let decoded = image::load_from_memory(source).map_err(OptimizeError::Decode)?;
131 let resized = resize_to(&decoded, target);
132
133 let main = match preferred_format {
139 FormatPreference::Avif => match encode_avif(&resized, quality) {
140 Ok(bytes) => Optimized {
141 bytes,
142 format: EncodedFormat::Avif,
143 },
144 Err(_) => Optimized {
145 bytes: encode_jpeg(&resized, quality)?,
146 format: EncodedFormat::Jpeg,
147 },
148 },
149 FormatPreference::Webp => match encode_webp(&resized, quality) {
150 Ok(bytes) => Optimized {
151 bytes,
152 format: EncodedFormat::Webp,
153 },
154 Err(_) => Optimized {
155 bytes: encode_jpeg(&resized, quality)?,
156 format: EncodedFormat::Jpeg,
157 },
158 },
159 FormatPreference::Jpeg => Optimized {
160 bytes: encode_jpeg(&resized, quality)?,
161 format: EncodedFormat::Jpeg,
162 },
163 };
164
165 let blur = if generate_blur {
166 let thumbnail = resize_to(&decoded, ResizeTarget::Width { width: BLUR_WIDTH });
167 encode_jpeg(&thumbnail, BLUR_QUALITY).ok()
168 } else {
169 None
170 };
171
172 Ok(OptimizeResult { main, blur })
173}
174
175fn resize_to(image: &image::DynamicImage, target: ResizeTarget) -> image::DynamicImage {
176 match target {
177 ResizeTarget::Exact { width, height } => {
178 image.resize_exact(width, height, FilterType::Lanczos3)
179 }
180 ResizeTarget::Width { width } => {
181 let (source_width, source_height) = (image.width().max(1), image.height().max(1));
182 let height =
183 ((source_height as u64 * width as u64) / source_width as u64).max(1) as u32;
184 image.resize_exact(width, height, FilterType::Lanczos3)
185 }
186 }
187}
188
189fn encode_avif(image: &image::DynamicImage, quality: u8) -> Result<Vec<u8>, OptimizeError> {
190 let rgba = image.to_rgba8();
191 let (width, height) = (rgba.width() as usize, rgba.height() as usize);
192 let pixels: Vec<rgb::RGBA8> = rgba
193 .pixels()
194 .map(|p| rgb::RGBA8::new(p[0], p[1], p[2], p[3]))
195 .collect();
196 let buffer = ravif::Img::new(pixels.as_slice(), width, height);
197
198 let result = ravif::Encoder::new()
199 .with_quality(quality as f32)
200 .with_speed(6)
201 .encode_rgba(buffer)
202 .map_err(|error| OptimizeError::Encode(error.to_string()))?;
203
204 Ok(result.avif_file)
205}
206
207fn encode_webp(image: &image::DynamicImage, quality: u8) -> Result<Vec<u8>, OptimizeError> {
218 let rgba = image.to_rgba8();
219 webpkit::encode_lossy_rgba(rgba.width(), rgba.height(), rgba.as_raw(), quality)
220 .map_err(|error| OptimizeError::Encode(error.to_string()))
221}
222
223fn encode_jpeg(image: &image::DynamicImage, quality: u8) -> Result<Vec<u8>, OptimizeError> {
224 use image::codecs::jpeg::JpegEncoder;
225
226 let mut bytes = Vec::new();
227 let rgb = image.to_rgb8();
228 JpegEncoder::new_with_quality(&mut bytes, quality)
229 .encode(
230 rgb.as_raw(),
231 rgb.width(),
232 rgb.height(),
233 image::ExtendedColorType::Rgb8,
234 )
235 .map_err(|error| OptimizeError::Encode(error.to_string()))?;
236 Ok(bytes)
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 fn tiny_png() -> Vec<u8> {
244 let mut buf = Vec::new();
251 let img = image::RgbImage::from_fn(40, 20, |x, y| {
252 image::Rgb([(x * 6) as u8, (y * 12) as u8, 128])
253 });
254 image::DynamicImage::ImageRgb8(img)
255 .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
256 .unwrap();
257 buf
258 }
259
260 #[test]
261 fn resizes_to_exactly_the_requested_box_and_encodes_jpeg() {
262 let result = optimize(
263 &tiny_png(),
264 ResizeTarget::Exact {
265 width: 10,
266 height: 20,
267 },
268 80,
269 FormatPreference::Jpeg,
270 false,
271 )
272 .unwrap();
273 assert_eq!(result.main.format, EncodedFormat::Jpeg);
274 assert!(result.blur.is_none());
275 let decoded = image::load_from_memory(&result.main.bytes).unwrap();
276 assert_eq!(decoded.width(), 10);
277 assert_eq!(decoded.height(), 20);
278 }
279
280 #[test]
281 fn width_only_target_preserves_the_sources_own_aspect_ratio() {
282 let result = optimize(
285 &tiny_png(),
286 ResizeTarget::Width { width: 20 },
287 80,
288 FormatPreference::Jpeg,
289 false,
290 )
291 .unwrap();
292 let decoded = image::load_from_memory(&result.main.bytes).unwrap();
293 assert_eq!(decoded.width(), 20);
294 assert_eq!(decoded.height(), 10);
295 }
296
297 #[test]
298 fn prefers_avif_when_requested_and_still_resizes_correctly() {
299 let result = optimize(
300 &tiny_png(),
301 ResizeTarget::Exact {
302 width: 8,
303 height: 8,
304 },
305 70,
306 FormatPreference::Avif,
307 false,
308 )
309 .unwrap();
310 assert_eq!(result.main.format, EncodedFormat::Avif);
311 assert!(!result.main.bytes.is_empty());
312 }
313
314 #[test]
315 fn prefers_webp_when_requested_and_still_resizes_correctly() {
316 let result = optimize(
317 &tiny_png(),
318 ResizeTarget::Exact {
319 width: 8,
320 height: 8,
321 },
322 70,
323 FormatPreference::Webp,
324 false,
325 )
326 .unwrap();
327 assert_eq!(result.main.format, EncodedFormat::Webp);
328 assert!(!result.main.bytes.is_empty());
329 }
330
331 #[test]
332 fn generates_a_small_blur_thumbnail_alongside_the_main_result() {
333 let result = optimize(
334 &tiny_png(),
335 ResizeTarget::Exact {
336 width: 200,
337 height: 100,
338 },
339 80,
340 FormatPreference::Jpeg,
341 true,
342 )
343 .unwrap();
344 let blur_bytes = result.blur.expect("blur was requested");
345 let blur_decoded = image::load_from_memory(&blur_bytes).unwrap();
346 assert_eq!(blur_decoded.width(), BLUR_WIDTH);
347 assert!(blur_bytes.len() < 2000);
351 }
352
353 #[test]
354 fn a_corrupt_source_is_a_decode_error_not_a_panic() {
355 let error = optimize(
356 b"not an image",
357 ResizeTarget::Exact {
358 width: 10,
359 height: 10,
360 },
361 75,
362 FormatPreference::Jpeg,
363 false,
364 )
365 .unwrap_err();
366 assert!(matches!(error, OptimizeError::Decode(_)));
367 }
368}