Merge pull request #4256 from uploadcare/fix-thumbnail-aspect-ratio

Better thumbnail aspect ratio preservation
This commit is contained in:
Andrew Murray 2019-12-16 20:32:05 +11:00 committed by GitHub
commit 52113a82b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 21 deletions

View File

@ -5,37 +5,43 @@ from .helper import PillowTestCase, hopper
class TestImageThumbnail(PillowTestCase):
def test_sanity(self):
im = hopper()
im.thumbnail((100, 100))
self.assertIsNone(im.thumbnail((100, 100)))
self.assert_image(im, im.mode, (100, 100))
self.assertEqual(im.size, (100, 100))
def test_aspect(self):
im = hopper()
im = Image.new("L", (128, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
self.assertEqual(im.size, (100, 100))
im = hopper().resize((128, 256))
im = Image.new("L", (128, 256))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (50, 100))
self.assertEqual(im.size, (50, 100))
im = hopper().resize((128, 256))
im = Image.new("L", (128, 256))
im.thumbnail((50, 100))
self.assert_image(im, im.mode, (50, 100))
self.assertEqual(im.size, (50, 100))
im = hopper().resize((256, 128))
im = Image.new("L", (256, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 50))
self.assertEqual(im.size, (100, 50))
im = hopper().resize((256, 128))
im = Image.new("L", (256, 128))
im.thumbnail((100, 50))
self.assert_image(im, im.mode, (100, 50))
self.assertEqual(im.size, (100, 50))
im = hopper().resize((128, 128))
im = Image.new("L", (128, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
self.assertEqual(im.size, (100, 100))
im = Image.new("L", (256, 162)) # ratio is 1.5802469136
im.thumbnail((33, 33))
self.assertEqual(im.size, (33, 21)) # ratio is 1.5714285714
im = Image.new("L", (162, 256)) # ratio is 0.6328125
im.thumbnail((33, 33))
self.assertEqual(im.size, (21, 33)) # ratio is 0.6363636364
def test_no_resize(self):
# Check that draft() can resize the image to the destination size
@ -46,4 +52,4 @@ class TestImageThumbnail(PillowTestCase):
# Test thumbnail(), where only draft() is necessary to resize the image
with Image.open("Tests/images/hopper.jpg") as im:
im.thumbnail((64, 64))
self.assert_image(im, im.mode, (64, 64))
self.assertEqual(im.size, (64, 64))

View File

@ -2137,11 +2137,11 @@ class Image:
# preserve aspect ratio
x, y = self.size
if x > size[0]:
y = int(max(y * size[0] / x, 1))
x = int(size[0])
y = max(round(y * size[0] / x), 1)
x = size[0]
if y > size[1]:
x = int(max(x * size[1] / y, 1))
y = int(size[1])
x = max(round(x * size[1] / y), 1)
y = size[1]
size = x, y
if size == self.size: