2015-02-11 50 views
3

我想使用Python根据以下2个条件调整任何图像的大小。当两边大于1280时使用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)。

回答

2

您可以通过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') 

Additionaly,您可以删除原始图像和重命名调整。

+0

你能解释一下你的代码吗? – kn3l 2015-08-12 11:30:53

相关问题