Python / Pillow:如何缩放图像

46 投票
2 回答
83753 浏览
提问于 2025-04-18 13:19

假设我有一张图片,大小是2322像素宽和4128像素高。我想把它缩小到宽和高都小于1028像素。

我不能使用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 个回答

22

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

没必要重新发明轮子,这里有一个现成的方法可以用,就是Image.thumbnail

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

这个方法可以确保生成的图片大小不会超过你设定的范围,同时还能保持图片的比例不变。

如果你指定PIL.Image.ANTIALIAS,它会使用一种高质量的缩小滤镜,这样缩放后的效果会更好,你可能也会想用这个。

撰写回答