Python / Pillow:如何缩放图像

时间:2014-07-14 20:57:56

标签: python python-imaging-library image-scaling pillow

假设我的图像是2322像素x 4128像素。如何缩放它以使宽度和高度都小于1028px?

我无法使用Image.resizehttps://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.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,但根据此示例(http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails)和此答案(How do I resize an image using PIL and maintain its aspect ratio?),提供宽度和高度以便创建缩略图。是否有任何功能可以采用新的宽度或新的高度(不是两者)并缩放整个图像?

2 个答案:

答案 0 :(得分:56)

Noo需要重新发明轮子,有Image.thumbnail方法可用于此:

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

确保结果大小不大于给定范围,同时保持宽高比。

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

答案 1 :(得分:14)

使用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)))