Improve rounding

This commit is contained in:
orlnub123 2020-02-21 23:30:35 +00:00
parent 64c08f4dba
commit 8f21d0ddf0
2 changed files with 14 additions and 3 deletions

View File

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

View File

@ -2240,13 +2240,20 @@ class Image:
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: