Python Image Library and KeyError: 'JPG'
Asked Answered
D

2

18

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?

Disembodied answered 5/5, 2016 at 10:57 Comment(0)
N
31

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)
Noelyn answered 5/5, 2016 at 11:2 Comment(0)
O
0
 new_img_name = input("Enter the name of the new image(with extention): ")
    ext=str(new_img_name.split(".")[1])
    format = 'JPEG' if ext.lower() == 'jpg' else ext.upper()
    newimg.save(new_img_name,format)
Olivaolivaceous answered 2/4, 2024 at 13:34 Comment(1)
bad code, doesnt handle multiple '.' that could be in file name, also poorly indented and possibly quite incorrect. what is your answer providing that the other accepted answer isn't?Taiga

© 2022 - 2025 — McMap. All rights reserved.