Skip to content

Commit

Permalink
Improve rounding
Browse files Browse the repository at this point in the history
  • Loading branch information
orlnub123 committed Feb 21, 2020
1 parent 64c08f4 commit 8f21d0d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
4 changes: 4 additions & 0 deletions Tests/test_image_thumbnail.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ def test_aspect():
im.thumbnail((50, 50))
assert im.size == (34, 50) # ratio is 0.68

im = Image.new("L", (100, 30)) # ratio is 3.333333333333
im.thumbnail((75, 75))
assert im.size == (75, 23) # ratio is 3.260869565217


def test_float():
im = Image.new("L", (128, 128))
Expand Down
13 changes: 10 additions & 3 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2240,13 +2240,20 @@ def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):
if x >= self.width and y >= self.height:
return

def round_aspect(number):
if x / y >= aspect:
key = lambda n: abs(aspect - n / y) # noqa: E731
else:
key = lambda n: abs(aspect - x / n) # noqa: E731
return max(min(math.floor(number), math.ceil(number), key=key), 1)

# preserve aspect ratio
aspect = self.width / self.height
if x / y >= aspect:
x = max(y * aspect, 1)
x = round_aspect(y * aspect)
else:
y = max(x / aspect, 1)
size = (round(x), round(y))
y = round_aspect(x / aspect)
size = (x, y)

box = None
if reducing_gap is not None:
Expand Down

0 comments on commit 8f21d0d

Please sign in to comment.