Skip to content

Commit d3ae7a1

Browse files
authored
Merge pull request #4088 from radarhere/fit
Do not calculate the crop width in Image.fit if it is already known
2 parents cabadff + 1809f46 commit d3ae7a1

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

Tests/test_imageops.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,16 @@ def test_1pxfit(self):
8181
newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35))
8282
self.assertEqual(newimg.size, (35, 35))
8383

84+
def test_fit_same_ratio(self):
85+
# The ratio for this image is 1000.0 / 755 = 1.3245033112582782
86+
# If the ratios are not acknowledged to be the same,
87+
# and Pillow attempts to adjust the width to
88+
# 1.3245033112582782 * 755 = 1000.0000000000001
89+
# then centering this greater width causes a negative x offset when cropping
90+
with Image.new("RGB", (1000, 755)) as im:
91+
new_im = ImageOps.fit(im, (1000, 755))
92+
self.assertEqual(new_im.size, (1000, 755))
93+
8494
def test_pad(self):
8595
# Same ratio
8696
im = hopper()

src/PIL/ImageOps.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,11 @@ def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
426426
output_ratio = float(size[0]) / size[1]
427427

428428
# figure out if the sides or top/bottom will be cropped off
429-
if live_size_ratio >= output_ratio:
429+
if live_size_ratio == output_ratio:
430+
# live_size is already the needed ratio
431+
crop_width = live_size[0]
432+
crop_height = live_size[1]
433+
elif live_size_ratio >= output_ratio:
430434
# live_size is wider than what's needed, crop the sides
431435
crop_width = output_ratio * live_size[1]
432436
crop_height = live_size[1]

0 commit comments

Comments
 (0)