Python/枕头:如何缩放imag

2024-05-20 10:59:54 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个2322px x 4128px的图像。如何缩放,使宽度和高度都小于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?),宽度和高度都是为了创建缩略图而提供的。是否有任何函数接受新宽度或新高度(不是两者都有)并缩放整个图像?


Tags: andthe图像image宽度高度readthedocswidth
2条回答

不需要重新发明轮子,这里有^{}方法可用于:

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

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

指定PIL.Image.ANTIALIAS将应用高质量的下采样过滤器以获得更好的大小调整结果,您可能也希望如此。

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

相关问题 更多 >