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

Dor*_*omi 7 python python-2.x image-resizing python-2.7

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

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

这是代码:

from PIL import Image
img = Image.open('car.jpg')
new_img = img.resize((500,500))
new_img.save('car_resized','jpg')
Run Code Online (Sandbox Code Playgroud)

AK4*_*K47 11

您需要将对save函数的调用中的format参数设置为'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)
Run Code Online (Sandbox Code Playgroud)


Om *_*Sao 7

这是解决方案:

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)
Run Code Online (Sandbox Code Playgroud)

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