Python:如何使用PIL模块调整图像大小

时间:2016-06-04 14:55:59

标签: python python-2.7 python-2.x image-resizing

我尝试将图片大小调整为500x500px,但出现了此错误:

File "C:\Python27\lib\site-packages\PIL\Image.py", line 1681, in save
     save_handler = SAVE[format.upper()] KeyError: 'JPG'

这是代码:

from PIL import Image
img = Image.open('car.jpg')
new_img = img.resize((500,500))
new_img.save('car_resized','jpg')

2 个答案:

答案 0 :(得分:8)

您需要在调用保存功能时将格式参数设置为' JPEG':

from PIL import Image
img = Image.open('car.jpg')
new_img = img.resize((500,500))
new_img.save("car_resized.jpg", "JPEG", optimize=True)

答案 1 :(得分:2)

这是解决方案:

from PIL import Image
img = Image.open('car.jpg')
new_img = img.resize((500,500), Image.ANTIALIAS)
quality_val = 90 ##you can vary it considering the tradeoff for quality vs performance
new_img.save("car_resized.jpg", "JPEG", quality=quality_val)

PIL中有重采样技术的清单,例如ANTIALIASBICUBICBILINEARCUBICANTIALIAS被认为最适合缩小规模。