17

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')
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Doromi
  • 173
  • 1
  • 1
  • 5

2 Answers2

31

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)
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
7

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.

Om Sao
  • 7,064
  • 2
  • 47
  • 61