From 337b225e0a122ef69c14dae6d60123f5d75c460e Mon Sep 17 00:00:00 2001 From: hecko Date: Sun, 14 Jun 2026 10:46:28 +0200 Subject: [PATCH 1/2] Fix 0-size edge case in ImageOps.contain --- src/PIL/ImageOps.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py index f0ae142b9ba..7752f7222ea 100644 --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -290,11 +290,11 @@ def contain( if im_ratio != dest_ratio: if im_ratio > dest_ratio: - new_height = round(image.height / image.width * size[0]) + new_height = max(1, round(image.height / image.width * size[0])) if new_height != size[1]: size = (size[0], new_height) else: - new_width = round(image.width / image.height * size[1]) + new_width = max(1, round(image.width / image.height * size[1])) if new_width != size[0]: size = (new_width, size[1]) return image.resize(size, resample=method) From d9d505a5b7e6840d82c15a66312786992b2f941a Mon Sep 17 00:00:00 2001 From: hecko Date: Sun, 14 Jun 2026 10:52:14 +0200 Subject: [PATCH 2/2] Add test --- Tests/test_imageops.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py index 31b7abecd60..5124d4ee6e0 100644 --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -128,6 +128,16 @@ def test_contain_round() -> None: assert new_im.height == 5 +def test_contain_0px() -> None: + im = Image.new("1", (1, 256), 1) + new_im = ImageOps.contain(im, (8, 8)) + assert new_im.width == 1 + + im = Image.new("1", (256, 1), 1) + new_im = ImageOps.contain(im, (8, 8)) + assert new_im.height == 1 + + @pytest.mark.parametrize( "image_name, expected_size", (