Do not calculate the crop width if it is already known

This commit is contained in:
Andrew Murray 2019-09-29 14:26:32 +10:00
parent 0118a8fdb0
commit 1809f46e0b
2 changed files with 15 additions and 1 deletions

View File

@ -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()

View File

@ -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]