Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Image Library and KeyError: 'JPG'

This works:

from PIL import Image, ImageFont, ImageDraw

def create_image_file(name='test.jpeg', ext='jpeg', size=(500, 500), color=(5, 179, 200)):
    file_obj = open(name, 'w')
    image = Image.new("RGBA", size=size, color=color)
    usr_font = ImageFont.truetype(
        "/Users/myuser/ENV/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf", 59)
    d_usr = ImageDraw.Draw(image)
    d_usr = d_usr.text((105, 280), "Test Image", (0, 0, 0), font=usr_font)
    image.save(file_obj, ext)
    file_obj.close()

if __name__ == '__main__':
    f = create_image_file()

But if I change the arguments to:

def create_image_file(name='test.jpg', ext='jpg', ...)

An exception is raised:

File "/Users/myuser/project/venv/lib/python2.7/site-packages/PIL/Image.py", line 1681, in save
    save_handler = SAVE[format.upper()]
KeyError: 'JPG'

And I need to work with user uploaded images that have .jpg as the extension. Is this a Mac specific problem? Is there something I can do to add the format data to the Image lib?

like image 978
fiacre Avatar asked May 05 '16 10:05

fiacre


1 Answers

The second argument of save is not the extension, it is the format argument as specified in image file formats and the format specifier for JPEG files is JPEG, not JPG.

If you want PIL to decide which format to save, you can ignore the second argument, such as:

image.save(name)

Note that in this case you can only use a file name and not a file object.

See the documentation of .save() method for details:

format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used.

Alternatively, you can check the extension and decide the format manually. For example:

def create_image_file(name='test.jpeg', ext='jpeg', size=(500, 500), color=(5, 179, 200)):
    format = 'JPEG' if ext.lower() == 'jpg' else ext.upper()
    ...
    image.save(file_obj, format)
like image 55
Selcuk Avatar answered Sep 17 '22 16:09

Selcuk