From 1809f46e0b44db3fb8de3c35363c70d879b79381 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 29 Sep 2019 14:26:32 +1000 Subject: [PATCH] Do not calculate the crop width if it is already known --- Tests/test_imageops.py | 10 ++++++++++ src/PIL/ImageOps.py | 6 +++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py index 85529a708..2cdbbe02f 100644 --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -81,6 +81,16 @@ class TestImageOps(PillowTestCase): newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35)) self.assertEqual(newimg.size, (35, 35)) + def test_fit_same_ratio(self): + # The ratio for this image is 1000.0 / 755 = 1.3245033112582782 + # If the ratios are not acknowledged to be the same, + # and Pillow attempts to adjust the width to + # 1.3245033112582782 * 755 = 1000.0000000000001 + # then centering this greater width causes a negative x offset when cropping + with Image.new("RGB", (1000, 755)) as im: + new_im = ImageOps.fit(im, (1000, 755)) + self.assertEqual(new_im.size, (1000, 755)) + def test_pad(self): # Same ratio im = hopper() diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py index cfdd5c02a..5052cb74d 100644 --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -426,7 +426,11 @@ def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)): output_ratio = float(size[0]) / size[1] # figure out if the sides or top/bottom will be cropped off - if live_size_ratio >= output_ratio: + if live_size_ratio == output_ratio: + # live_size is already the needed ratio + crop_width = live_size[0] + crop_height = live_size[1] + elif live_size_ratio >= output_ratio: # live_size is wider than what's needed, crop the sides crop_width = output_ratio * live_size[1] crop_height = live_size[1]