2016-05-05 146 views
2

这工作:Python的图片库和KeyError异常: 'JPG'

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

但是,如果我改变参数:

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

将引发异常:

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

而且我需要使用以.jpg作为扩展名的用户上传图片。这是一个Mac特定的问题?有什么我可以做的将格式数据添加到图像库?

回答

5

save第二个参数是的延长,它是作为在image file formats指定并且格式说明为JPEG文件是JPEG,不JPG的格式参数。

如果你想PIL决定哪种格式保存,你可以忽略第二个参数,如:

image.save(name) 

注意,在这种情况下,你只能使用一个文件名,而不是一个文件对象。

有关详细信息,请参阅documentation of .save() method

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.

或者,您可以检查的延伸和手动决定的格式。例如:

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)