Python: How to resize an image using PIL module

Doromi picture Doromi · Jun 4, 2016 · Viewed 26.2k times · Source

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

Answer

AK47 picture AK47 · Jun 4, 2016

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)