Skip to main content

aer/proc/
image.rs

1use std::io::Cursor;
2
3use image::ImageFormat;
4
5use super::{Asset, Environment, LayeredContext, MediaCategory, ProcessesAssets, ProcessingError};
6
7/// Resizes images to fit within a given width and height,
8/// preserving the image's original aspect ratio.
9///
10/// If the image is already within the given width and height,
11/// this processor does nothing.
12///
13/// This processor uses a [Lanczos](https://mazzo.li/posts/lanczos.html)
14/// filter when resizing images. This filter is one of the slowest, but
15/// produces consistently high-quality results, making it best suited
16/// for processing _static_ content.
17pub struct ImageResizeProcessor {
18    /// The maximum width of the resized image.
19    width: u32,
20
21    /// The maximum height of the resized image.
22    height: u32,
23}
24
25impl ImageResizeProcessor {
26    pub fn new(width: u32, height: u32) -> Self {
27        Self { width, height }
28    }
29}
30
31impl ProcessesAssets for ImageResizeProcessor {
32    fn process(
33        &self,
34        _env: &Environment,
35        _context: &LayeredContext,
36        asset: &mut Asset,
37    ) -> Result<bool, ProcessingError> {
38        // Skip assets that aren't images.
39        if asset.media_type().category() != MediaCategory::Image {
40            return Ok(false);
41        }
42
43        // Extract image bytes.
44        let asset_path = asset.path().clone();
45        let image_format = ImageFormat::from_path(asset_path.as_str()).map_err(|e| {
46            ProcessingError::Malformed {
47                message: e.to_string().into(),
48            }
49        })?;
50        let image_bytes = asset.as_mut_bytes()?;
51        let image =
52            image::load_from_memory(image_bytes).map_err(|e| ProcessingError::Malformed {
53                message: e.to_string().into(),
54            })?;
55
56        // Skip resizing if the image is already inside the bounding box.
57        if image.width() <= self.width && image.height() <= self.height {
58            return Ok(false);
59        }
60
61        tracing::trace!("image: {}", asset_path);
62
63        // Resize the image to fit the bounding box.
64        let image = image.resize(
65            self.width,
66            self.height,
67            image::imageops::FilterType::Lanczos3,
68        );
69
70        // Write resized image.
71        image_bytes.clear();
72        let mut cursor = Cursor::new(image_bytes);
73        image
74            .write_to(&mut cursor, image_format)
75            .map_err(|e| ProcessingError::Malformed {
76                message: e.to_string().into(),
77            })?;
78
79        Ok(true)
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::proc::LayeredContext;
87
88    #[test_log::test]
89    #[test_log(default_log_filter = "debug")]
90    fn resizes_image() {
91        let _ = tracing_subscriber::fmt()
92            .with_max_level(tracing::Level::DEBUG)
93            .with_test_writer()
94            .try_init();
95
96        let source_bytes = std::fs::read("test/example.png").unwrap();
97
98        // Wrap the source image in an asset.
99        let mut asset = Asset::new("test/example.png".into(), source_bytes.clone());
100
101        // Resize the image.
102        let (width, height) = (300, 300);
103        ImageResizeProcessor { width, height }
104            .process(
105                &Environment::test(),
106                &LayeredContext::from_flat(Default::default()),
107                &mut asset,
108            )
109            .unwrap();
110
111        // Check the dimensions of the resized image.
112        let resized_image = image::load_from_memory(asset.as_bytes()).unwrap();
113        assert_eq!(width, resized_image.width());
114        assert_eq!(243, resized_image.height());
115    }
116
117    #[test]
118    fn skips_image_already_within_bounds() {
119        let source_bytes = std::fs::read("test/example.png").unwrap();
120        let original_bytes = source_bytes.clone();
121
122        let mut asset = Asset::new("photo.png".into(), source_bytes);
123
124        // Use dimensions larger than the test image.
125        let modified = ImageResizeProcessor::new(9999, 9999)
126            .process(
127                &Environment::test(),
128                &LayeredContext::from_flat(Default::default()),
129                &mut asset,
130            )
131            .unwrap();
132
133        assert!(!modified);
134        assert_eq!(asset.as_bytes(), &original_bytes);
135    }
136
137    #[test]
138    fn skips_non_image_assets() {
139        let mut asset = Asset::new("style.css".into(), b"body {}".to_vec());
140        let modified = ImageResizeProcessor::new(300, 300)
141            .process(
142                &Environment::test(),
143                &LayeredContext::from_flat(Default::default()),
144                &mut asset,
145            )
146            .unwrap();
147        assert!(!modified);
148    }
149}