From e9ef1d236dcc964c186f76156aeff5db186a2708 Mon Sep 17 00:00:00 2001 From: orlnub123 Date: Tue, 4 Feb 2020 20:14:00 +0000 Subject: [PATCH] Fix size calculation of Image.thumbnail() --- Tests/test_image_thumbnail.py | 8 ++++++++ src/PIL/Image.py | 17 ++++++++--------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/Tests/test_image_thumbnail.py b/Tests/test_image_thumbnail.py index de15f5e2e..4c7e8982a 100644 --- a/Tests/test_image_thumbnail.py +++ b/Tests/test_image_thumbnail.py @@ -50,6 +50,14 @@ def test_aspect(): im.thumbnail((33, 33)) assert im.size == (21, 33) # ratio is 0.6363636364 + im = Image.new("L", (145, 100)) # ratio is 1.45 + im.thumbnail((50, 50)) + assert im.size ==(50, 34) # ratio is 1.47058823529 + + im = Image.new("L", (100, 145)) # ratio is 0.689655172414 + im.thumbnail((50, 50)) + assert im.size == (34, 50) # ratio is 0.68 + def test_float(): im = Image.new("L", (128, 128)) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index dec94f2d0..e1ae4a678 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2237,19 +2237,18 @@ class Image: """ # preserve aspect ratio - x, y = self.size - if x > size[0]: - y = max(round(y * size[0] / x), 1) - x = round(size[0]) - if y > size[1]: - x = max(round(x * size[1] / y), 1) - y = round(size[1]) - size = x, y - box = None + x, y = size + aspect = self.width / self.height + if x / y >= aspect: + x = max(y * aspect, 1) + else: + y = max(x / aspect, 1) + size = (round(x), round(y)) if size == self.size: return + box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: