Skip to main content

larust_image/
optimize.rs

1//! Decode, resize, and re-encode one image - the actual work behind
2//! [`crate::route::ImagePlugin`]'s one route. Pure, synchronous, and I/O-
3//! free (the caller reads the source file's bytes and writes the result
4//! to the cache); kept separate from [`crate::route`] so the resize/encode
5//! logic itself is testable without a real `axum` request or filesystem.
6
7use image::imageops::FilterType;
8use image::ImageError;
9
10/// How to resize the decoded source - see [`optimize`]'s own doc comment
11/// for when each is used.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ResizeTarget {
14    /// The common case: `<Image width="..." height="..." />` with both
15    /// given - resize to exactly this box, cropping/stretching as needed,
16    /// never preserving the source's own aspect ratio. Laying out a fixed
17    /// box is the whole point of giving both dimensions explicitly.
18    Exact { width: u32, height: u32 },
19    /// `fill="true"`, or a `sizes`-driven `srcset` variant - only a target
20    /// *width* is known; height is derived from the source's own aspect
21    /// ratio instead of being forced into an arbitrary box. Different
22    /// breakpoints/layouts legitimately want different heights for the
23    /// same source image, so forcing one fixed height across every
24    /// variant (the way [`ResizeTarget::Exact`] does for a single,
25    /// explicitly-boxed image) would be wrong here.
26    Width { width: u32 },
27}
28
29/// Which format [`optimize`] actually produced - the caller needs this to
30/// pick the right `Content-Type`/cache file extension, since it depends on
31/// the request's own `Accept` header, not just the input.
32#[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/// Which format [`optimize`] should *try* first, decided by the caller
58/// from the request's own `Accept` header - `Avif` wins over `Webp` when
59/// both are accepted (the ordinary case: a browser that accepts AVIF
60/// almost always lists it ahead of WebP in `Accept`, and AVIF compresses
61/// better at equal quality). Each lossy tier falls back to
62/// [`EncodedFormat::Jpeg`] on a real encode failure - see [`optimize`]'s
63/// own match arm for why that's always safe to do silently.
64#[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/// [`optimize`]'s full result - the main resized/encoded image, plus
78/// (when asked for) a tiny blurred thumbnail generated from the *same*
79/// decode, so producing one never costs a second, separate decode of the
80/// source file. See [`crate::route`]'s own doc comment for why the blur
81/// thumbnail is generated here, as a side effect of an ordinary optimize
82/// request, rather than computed synchronously inside [`crate::tag`].
83#[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
106/// A tiny, heavily-compressed thumbnail width for blur placeholders - wide
107/// enough to carry real color/shape information once blurred by CSS
108/// (`background-size: cover` upscaling), narrow enough that even a large
109/// source image's blur variant is a few hundred bytes at most, since it's
110/// inlined directly into the page's own HTML as a base64 data URI (see
111/// `crate::tag`'s own doc comment) rather than fetched separately.
112const BLUR_WIDTH: u32 = 16;
113const BLUR_QUALITY: u8 = 30;
114
115/// Decodes `source` once, resizes it per `target` for the main result -
116/// `preferred_format` (the caller decides this from the request's own
117/// `Accept` header) when that format's own encoder succeeds, JPEG
118/// otherwise - and, when `generate_blur` is set, *also* produces a tiny
119/// blurred-placeholder thumbnail from the same decode (always JPEG,
120/// regardless of `preferred_format` - it's consumed directly by the
121/// browser's own CSS decoder as an inline data URI, never served as a
122/// standalone resource a format negotiation could apply to).
123pub 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    // Both lossy tiers below share the identical "fall through to JPEG on
134    // a real encode failure" reasoning: this is never a capability gap
135    // (every input this crate decodes is RGBA8-convertible), so a
136    // slightly bigger JPEG beats a 500 for an image that would otherwise
137    // have rendered fine.
138    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
207/// `webpkit` 0.1 - see this workspace's own root `Cargo.toml` comment on
208/// the `webpkit` dependency for why this exists at all (a pure-Rust lossy
209/// WebP encoder, picked over the more mature `zenwebp` purely over its
210/// `AGPL`/commercial license) and `crate`'s own module doc comment for the
211/// honesty caveat this carries into the public `<Image>` docs - this is
212/// genuinely pre-1.0 upstream, with no published conformance/benchmark
213/// results of its own yet, unlike [`encode_avif`]'s `ravif`.
214/// `encode_lossy_rgba` takes a raw, tightly-packed RGBA8 buffer directly -
215/// no per-pixel remapping into an intermediate pixel type the way
216/// `encode_avif`'s own `rgb::RGBA8` buffer needs for `ravif`'s API.
217fn 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        // A real, minimal PNG, generated once via `image` itself rather
245        // than hand-written bytes - simplest way to get a guaranteed-valid
246        // fixture without shipping a binary test asset. 40x20 (2:1), wide
247        // enough that `ResizeTarget::Width`'s own proportional-height math
248        // is actually exercised (a square fixture would hide a transposed
249        // width/height bug).
250        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        // Source is 40x20 (2:1) - asking for width 20 should derive height
283        // 10, not stretch/crop into some other ratio.
284        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        // Blur bytes are a tiny fraction of a real photo's size - not a
348        // precise bound, just confirms it's genuinely a thumbnail, not
349        // accidentally a full-size encode.
350        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}