【问题标题】:Python / Pillow: How to scale an imagePython / Pillow:如何缩放图像
【发布时间】:2014-09-04 22:04:39
【问题描述】:

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

我将无法使用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)

我猜我需要使用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?),提供了宽度和高度以创建缩略图。是否有任何函数可以采用新宽度或新高度(不是两者)并缩放整个图像?

【问题讨论】:

  • Image.thumbnail 提供宽度和高度有什么问题?你想用你的自定义代码做到这一点。

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


【解决方案1】:

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

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

确保生成的大小不大于给定的边界,同时保持纵横比。

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

【讨论】:

  • 哦,我误解了缩略图的作用。我以为 image.thumbnail(1028, 1028) 将图像大小调整为 1028 宽度和 1028 高度...我不知道 image.thumbnail(1028, 1028) 缩放图像以使宽度和高度都小于 1028
  • @user2719875 我强烈建议添加Image.ANTIALIAS 参数。
  • 如果使用 Pillow >= 2.5.0,Image.ANTIALIASdefaultImage.thumbnail()
  • 注意根据documentation"注意这个函数在原地修改Image对象。如果你也需要使用全分辨率图像,请将此方法应用于原图。”
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2019-05-07
    • 2013-05-29
    相关资源
    最近更新 更多