使用Python在任一sid上大于1280时调整图像大小

2024-06-09 23:25:36 发布

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

我想使用Python根据以下两个条件调整任何图像的大小。在

1)如果图像是横向的,则获取宽度,如果大于1280请将图像宽度调整为1280保持纵横比。在

2)如果图像是纵向的,则获取高度,如果大于1280请将高度调整为1280保持纵横比。在

在Python中,实现这一点的最佳包/方法是什么?不知道该用什么,这就是我如何看待它的工作方式。在

伪代码:

If image.height > image.width:
  size = image.height

If image.height < image.width:
  size = image.width

If size > 1280:
  resize maintaining aspect ratio

我在看Pillow(PIL)。在


Tags: 方法代码图像imagesizeif宽度高度
1条回答
网友
1楼 · 发布于 2024-06-09 23:25:36

你可以通过PIL,类似这样:

import Image

MAX_SIZE = 1280
image = Image.open(image_path)
original_size = max(image.size[0], image.size[1])

if original_size >= MAX_SIZE:
    resized_file = open(image_path.split('.')[0] + '_resized.jpg', "w")
    if (image.size[0] > image.size[1]):
        resized_width = MAX_SIZE
        resized_height = int(round((MAX_SIZE/float(image.size[0]))*image.size[1])) 
    else:
        resized_height = MAX_SIZE
        resized_width = int(round((MAX_SIZE/float(image.size[1]))*image.size[0]))

    image = image.resize((resized_width, resized_height), Image.ANTIALIAS)
    image.save(resized_file, 'JPEG')

此外,您可以删除原始图像和重命名调整大小。在

相关问题 更多 >