简体   繁体   English

Python 图像库和 KeyError:'JPG'

[英]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.而且我需要使用用户上传的以.jpg作为扩展名的图像。 Is this a Mac specific problem?这是 Mac 特有的问题吗? Is there something I can do to add the format data to the Image lib?我可以做些什么来将格式数据添加到 Image lib 中吗?

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 . save的第二个参数不是扩展名,它是图像文件格式中指定的格式参数,JPEG 文件的格式说明符是JPEG ,而不是JPG

If you want PIL to decide which format to save, you can ignore the second argument, such as:如果希望PIL决定保存哪种格式,可以忽略第二个参数,例如:

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:有关详细信息,请参阅.save()方法的文档

format – Optional format override. format -- 可选的格式覆盖。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM