Skip to main content

dimensions: fix a rounding error for images with extreme aspect ratios

ID
35224b6
date
2026-09-24 05:08:37+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
526f256
message
dimensions: fix a rounding error for images with extreme aspect ratios
changed files
1 file, 6 additions, 6 deletions

Changed files

src/dimensions.rs (5023 → 5106)

diff --git a/src/dimensions.rs b/src/dimensions.rs
index 62ddf80..7572c7d 100644
--- a/src/dimensions.rs
+++ b/src/dimensions.rs
@@ -23,10 +23,10 @@ impl TargetDimension {
 
             TargetDimension::MaxWidth(max_w) => (
                 max_w,
-                ((max_w as f64) * (img_h as f64) / (img_w as f64)).round() as u32,
+                (((max_w as f64) * (img_h as f64) / (img_w as f64)).round() as u32).max(1),
             ),
             TargetDimension::MaxHeight(max_h) => (
-                ((max_h as f64) * (img_w as f64) / (img_h as f64)).round() as u32,
+                (((max_h as f64) * (img_w as f64) / (img_h as f64)).round() as u32).max(1),
                 max_h,
             ),
 
@@ -47,10 +47,6 @@ impl TargetDimension {
 ///
 /// Leaves the image at its original size if it's already smaller than
 /// the target constraints.
-///
-/// TODO: Are there any scenarios in which this division could round
-/// one dimension of an image to zero, if it was very tall or very long?
-///
 pub fn thumbnail_dimensions(
     path: impl AsRef<Path>,
     target: TargetDimension,
@@ -114,6 +110,10 @@ mod test_thumbnail_dimensions {
         // aren't making rounding errors
         fp_width:  ((500, 333), TargetDimension::MaxWidth(300),  (300, 200)),
         fp_height: ((333, 500), TargetDimension::MaxHeight(300), (200, 300)),
+
+        // extreme images that could be rounded to zero
+        extreme_width:  ((10000, 1), TargetDimension::MaxWidth(10),  (10, 1)),
+        extreme_height: ((1, 10000), TargetDimension::MaxHeight(10), (1, 10)),
     }
 
     #[test]