Skip to content

Commit

Permalink
Merge pull request #4088 from radarhere/fit
Browse files Browse the repository at this point in the history
Do not calculate the crop width in Image.fit if it is already known
  • Loading branch information
hugovk committed Sep 29, 2019
2 parents cabadff + 1809f46 commit d3ae7a1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Tests/test_imageops.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ def test_1pxfit(self):
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()
Expand Down
6 changes: 5 additions & 1 deletion src/PIL/ImageOps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit d3ae7a1

Please sign in to comment.