Python/Pillow:如何缩放图像

use*_*875 32 python python-imaging-library image-scaling pillow

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

我将无法使用Image.resize(https://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)
Run Code Online (Sandbox Code Playgroud)

我猜我需要使用Image.thumbnail,但根据这个例子(http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails)和这个答案(如何使用PIL调整图像大小并保持其宽高比?),提供宽度和高度以创建缩略图.是否有任何功能可以采用新的宽度或新的高度(不是两者)并缩放整个图像?

fam*_*kin 62

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

maxsize = (1028, 1028)
image.thumbnail(maxsize, PIL.Image.ANTIALIAS)
Run Code Online (Sandbox Code Playgroud)

确保最终尺寸不大于给定边界,同时保持纵横比.

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

  • 如果使用Pillow> = 2.5.0,`Image.ANTIALIAS`是[Image.thumbnail()`的[默认](https://github.com/python-pillow/Pillow/commit/22a370afc219af47907b2fe69e791854dd2d9c79). (3认同)
  • 哦,我误解了缩略图是做什么的.我认为image.thumbnail(1028,1028)将图像大小调整为1028宽度和1028高度...我不知道image.thumbnail(1028,1028)缩放图像,使宽度和高度都小于1028 (2认同)
  • @ user2719875我强烈建议添加`Image.ANTIALIAS`参数. (2认同)
  • 请注意,根据[文档](https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail)“请注意,此函数会就地修改 Image 对象.如果您还需要使用全分辨率图像,请将此方法应用于原始图像的 copy()。” (2认同)

Soh*_*a82 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)))
Run Code Online (Sandbox Code Playgroud)