2016-05-05 144 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)