Python: How to resize an image using PIL module

主宰稳场 提交于 2019-11-28 07:31:54

问题


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

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')

回答1:


You need to set the format parameter in your call to the save function to '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)



回答2:


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, BILINEAR and CUBIC. ANTIALIAS is considered best for scaling down.



来源:https://stackoverflow.com/questions/37631611/python-how-to-resize-an-image-using-pil-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!