tapciify/
resize.rs

1//! Utils for resizing your images, but including your font ratio
2
3use image::imageops;
4
5/// Consolas font family aspect ratio
6pub const DEFAULT_FONT_RATIO: f64 = 11.0 / 24.0;
7
8/// Trait for resizing images and counting in font ratio
9pub trait CustomRatioResize {
10    /// Resize [`image::DynamicImage`] to your sizes
11    /// When both `width` and `height` are [`None`], will return the original [`image::DynamicImage`]
12    ///
13    /// # Examples
14    ///
15    /// ```
16    /// use image::imageops::FilterType;
17    /// use tapciify::{CustomRatioResize, DEFAULT_FONT_RATIO};
18    ///
19    /// # fn main() -> Result<(), image::ImageError> {
20    /// let img = image::open("./assets/examples/ferris.webp")?;
21    ///
22    /// let result = img.resize_custom_ratio(Some(64), None, DEFAULT_FONT_RATIO, FilterType::Triangle);
23    /// # Ok(())
24    /// # }
25    /// ```
26    fn resize_custom_ratio(
27        &self,
28        width: Option<u32>,
29        height: Option<u32>,
30        font_ratio: f64,
31        filter: imageops::FilterType,
32    ) -> image::DynamicImage;
33}
34
35impl CustomRatioResize for image::DynamicImage {
36    fn resize_custom_ratio(
37        &self,
38        width: Option<u32>,
39        height: Option<u32>,
40        font_ratio: f64,
41        filter: imageops::FilterType,
42    ) -> image::DynamicImage {
43        let (new_width, new_height) = match (width, height) {
44            (None, None) => return self.to_owned(),
45            (None, Some(height)) => (
46                calc_new_width(height, self.width(), self.height(), font_ratio),
47                height,
48            ),
49            (Some(width), None) => (
50                width,
51                calc_new_height(width, self.width(), self.height(), font_ratio),
52            ),
53            (Some(width), Some(height)) => (width, height),
54        };
55
56        self.resize_exact(new_width, new_height, filter)
57    }
58}
59
60/// Calculate new width from aspect ratio and new height
61pub fn calc_new_width(new_height: u32, width: u32, height: u32, font_ratio: f64) -> u32 {
62    ((new_height * width) as f64 / (height as f64 * font_ratio)) as u32
63}
64
65/// Calculate new height from aspect ratio and new width
66pub fn calc_new_height(new_width: u32, width: u32, height: u32, font_ratio: f64) -> u32 {
67    (new_width as f64 * font_ratio * height as f64 / width as f64) as u32
68}