简体   繁体   English

Python / Pillow:如何缩放图像

[英]Python / Pillow: How to scale an image

Suppose I have an image which is 2322px x 4128px. 假设我的图像是2322像素x 4128像素。 How do I scale it so that both the width and height are both less than 1028px? 如何缩放它以使宽度和高度都小于1028px?

I won't be able to use Image.resize ( https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize ) since that requires me to give both the new width and height. 我将无法使用Image.resizehttps://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize ),因为这需要我同时给出新的宽度和高度。 What I plan to do is (pseudo code below): 我打算做的是(下面的伪代码):

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)

I am guessing I need to use Image.thumbnail , but according to this example ( http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails ) and this answer ( How do I resize an image using PIL and maintain its aspect ratio? ), both the width and the height are provided in order to create the thumbnail. 我猜我需要使用Image.thumbnail ,但根据这个例子( http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails )和这个答案( 我如何调整大小使用PIL并保持其宽高比? )的图像,提供宽度和高度以创建缩略图。 Is there any function which takes either the new width or the new height (not both) and scales the entire image? 是否有任何功能可以采用新的宽度或新的高度(不是两者)并缩放整个图像?

Noo need to reinvent the wheel, there is the Image.thumbnail method available for this: Noo需要重新发明轮子, Image.thumbnail方法可用于此:

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

Ensures the resulting size is not bigger than the given bounds while maintains the aspect ratio. 确保最终尺寸不大于给定边界,同时保持纵横比。

Specifying PIL.Image.ANTIALIAS applies a high-quality downsampling filter for better resize result, you probably want that too. 指定PIL.Image.ANTIALIAS应用高质量的下采样过滤器以获得更好的调整大小结果,您可能也需要它。

Use Image.resize, but calculate both width and height. 使用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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM