如何使用Python PIL(枕头)将图像保存在特定的文件目录中,而不会出现KeyError,原因是:save_handler = SAVE [format.upper()]

时间:2018-07-10 14:56:56

标签: python pillow keyerror

我正在尝试从元素周期表的较大图像中裁剪特定元素,然后将其保存在特定文件目录中,此文件目录位于其他文件夹中,并且此文件夹与程序位于同一文件目录中我正试图做到这一点。

我看过另一个关于堆栈溢出的已回答问题,该问题与我的问题相似: How can I save an image with PIL? ,但是该用户使用了'numpy'。我以前只是在学校里学习过python基础知识,现在正在利用我的空闲时间来学习“ tkinter”,现在又是“ PIL”(枕头),对于这些python模块我是陌生的,并且我正努力抓住这两个令人困惑的文档,还不知道“ numpy”是什么或如何使用。

这是我要运行的代码:

#Saving G1 elements as their own image


from PIL import Image


Periodic_Table = Image.open("Periodic Table Bitmap.bmp")
G1_List = ["Hydrogen.bmp","Lithium.bmp","Sodium.bmp",
           "Potassium.bmp","Rubidium.bmp","Caesium.bmp","Francium.bmp"]

starting_coords = (180,86,340,271)
for i in range(7):
    y1 = 86 + (i * 187)
    y2 = 86 + ((i+1)* 187) - 3
    cropped_region = (180,y1,340,y2)
    G1_Element = Periodic_Table.crop(cropped_region)
    G1_Name = G1_List[i]
    G1_Element.save(
        "C:\\Users\\Kids\\Documents\\Robert\\Python Programming\\Periodic Table Quiz\\PIL Programs and Images\\Group 1 Elements"
        , G1_Name)

我也尝试过运行相同的代码,其中G1_List中的项目不具有'.bmp'扩展名,但是图像名称的格式设置如下:

#Saving G1 elements as their own image

from PIL import Image

Periodic_Table = Image.open("Periodic Table Bitmap.bmp")
G1_List = ["Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium"]

starting_coords = (180,86,340,271)
for i in range(7):
    y1 = 86 + (i * 187)
    y2 = 86 + ((i+1)* 187) - 3
    cropped_region = (180,y1,340,y2)
    G1_Element = Periodic_Table.crop(cropped_region)
    G1_Name = G1_List[i]
    G1_Name_Formatted = ("%s" % (G1_Name)) + ".bmp"
    G1_Element.save(
        "C:\\Users\\Kids\\Documents\\Robert\\Python Programming\\Periodic Table Quiz\\PIL Programs and Images\\Group 1 Elements"
        , G1_Name_Formatted)

在两种情况下,我都收到此错误消息:

save_handler = SAVE[format.upper()]
KeyError: 'HYDROGEN.BMP'

在我将链接粘贴到之前的文章中,建议删除“。”来自'.bmp'的扩展名,因此可以识别大写形式的扩展名,但这也不起作用。

任何解决方案将不胜感激,最好不使用诸如numpy之类的附加模块,但是,如果必须使用其中的任何模块,我将不熟悉它们,并且需要答案中的代码向我解释如果我理解的话,完全可以。

注意:我使用位图图像是因为我在某些python文档中了解到,我计划与PIL(枕头)一起使用的tkinter仅与位图图像兼容:https://pillow.readthedocs.io/en/5.2.x/reference/ImageTk.html

谢谢

1 个答案:

答案 0 :(得分:1)

您要将文件名作为第二个参数传递给Image.save

但是,第二个参数是(可选)文件格式-如果指定,则它必须与注册的文件格式匹配,例如GIFBMPPNG,...

您可能想要做的是将路径和图像名称连接起来-无需指定格式。

import os

...

# dir_path can be set outside of your loop
dir_path = "C:\\Users\\Kids\\Documents\\Robert\\Python Programming\\Periodic Table Quiz\\PIL Programs and Images\\Group 1 Elements"
...
G1_Name_Formatted = ("%s" % (G1_Name)) + ".bmp"
file_path = os.path.join( dir_path, G1_Name_Formatted  ) 
G1_Element.save( file_path )

或者如果您要明确指定格式,请将最后一部分更改为:

G1_Element.save( file_path, "BMP" )