Python/Pillow:如何缩放图片

45

假设我有一张图片大小为2322px x 4128px。如何缩放它以使宽度和高度都小于1028px?

由于使用Image.resize需要提供新的宽度和高度,所以无法使用该方法。我的计划是(以下是伪代码):

if (image.width or image.height) > 1028:
    if image.width > image.height:
        tn_image = image.scale(make width of image 1028)
        # since the height is less than the width and I am scaling the image
        # and making the width less than 1028px, the height will surely be
        # less than 1028px
    else: #image's height is greater than it's width
        tn_image = image.scale(make height of image 1028)

我猜我需要使用Image.thumbnail,但是根据这个例子这个答案,创建缩略图需要提供宽度和高度。是否有任何函数可以只取新的宽度或新的高度(而不是两者),并缩放整个图像?


2
提供宽度和高度给 Image.thumbnail 存在什么问题?你想用自己的代码实现这个功能。 - famousgarkin
2个回答

93

没有必要重新发明轮子,因为有Image.thumbnail方法可用:

maxsize = (1028, 1028)
image.thumbnail(maxsize, PIL.Image.ANTIALIAS)

在保持宽高比的同时,确保结果大小不超过给定的边界。

指定PIL.Image.ANTIALIAS会应用高质量的下采样滤波器以获得更好的调整大小结果,您可能也需要这样做。


3
哦,我误解了缩略图的作用。我以为image.thumbnail(1028, 1028)会将图像调整为宽度和高度均为1028像素大小...我不知道image.thumbnail(1028, 1028)是将图像缩放,使得宽度和高度都小于1028像素。 - SilentDev
2
@user2719875,我强烈建议添加Image.ANTIALIAS参数。 - Mark Ransom
4
如果使用 Pillow >= 2.5.0 版本,Image.thumbnail() 方法默认会使用 Image.ANTIALIAS 参数进行缩略处理。 - Hugo
2
请注意,根据文档,“请注意,此函数会直接修改原始图像对象。如果您需要同时使用完整分辨率的图像,请将此方法应用于原始图像的副本(copy())。” - mapto

21

使用Image.resize,但同时计算宽度和高度。

if image.width > 1028 or image.height > 1028:
    if image.height > image.width:
        factor = 1028 / image.height
    else:
        factor = 1028 / image.width
    tn_image = image.resize((int(image.width * factor), int(image.height * factor)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接