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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37631611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:41:54  来源:igfitidea点击:

Python: How to resize an image using PIL module

pythonpython-2.7python-2.ximage-resizing

提问by Doromi

I'm trying to resize an image to 500x500px but got this error:

我正在尝试将图像大小调整为 500x500 像素,但出现此错误:

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

This is the code:

这是代码:

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

回答by AK47

You need to set the format parameter in your call to the save function to 'JPEG':

您需要在调用 save 函数时将格式参数设置为“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)

回答by Om Sao

Here is the solution:

这是解决方案:

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)

There are list of resampling techniques in PIL like ANTIALIAS, BICUBIC, BILINEARand CUBIC. ANTIALIASis considered best for scaling down.

有PIL中重采样技术,如清单ANTIALIASBICUBICBILINEARCUBICANTIALIAS被认为是缩小规模的最佳选择。