2017-07-13 103 views
1

是否可以獲取已從Image對象打開的圖像的文件名?我檢查了API,最好的是PIL.Image.info,但是當我檢查它時,這似乎是空的。 還有什麼我可以用來獲得這個信息在PIL圖像庫嗎?從圖像PIL中獲取圖像文件名

(是的,我知道我可以傳遞文件名到函數。我正在尋找另一種方式來做到這一點。)

from PIL import Image 

def foo_img(img_input): 
    filename = img_input.info["filename"] 
    # I want this to print '/path/to/some/img.img' 
    print(filename) 

foo_img(Image.open('/path/to/some/img.img')) 
+0

因爲您是打開文件的人,爲什麼不直接保存文件名呢? –

+0

@BryanOakley在括號中看我的筆記。 除非你的意思是,我可以將它保存在信息詞典中?在這種情況下,這是一個答案,你可以寫出來。 –

+0

想想這個的方式可能是,我正在寫foo_img(),而其他人正在調用它。我希望將img_input作爲我函數的唯一輸入。有沒有辦法讓我獲得文件名而不需要爲我的函數添加輸入? –

回答

3

我不知道這是任何地方的記載,但單純用dir我開了一個圖像上顯示的屬性叫filename

>>> im = Image.open(r'c:\temp\temp.jpg') 
>>> im.filename 
'c:\\temp\\temp.jpg' 

可惜你不能保證該屬性將在對象上:

>>> im2 = Image.new('RGB', (100,100)) 
>>> im2.filename 
Traceback (most recent call last): 
    File "<pyshell#50>", line 1, in <module> 
    im2.filename 
AttributeError: 'Image' object has no attribute 'filename' 

您可以使用try/except搭上AttributeError解決這個問題搞定了,或者你在您嘗試使用它之前可以測試以查看對象是否具有文件名:

>>> hasattr(im, 'filename') 
True 
>>> hasattr(im2, 'filename') 
False 
>>> if hasattr(im, 'filename'): 
    print(im.filename) 

c:\temp\temp.jpg 
+0

你是對的,它沒有記錄,但它確實存在。 謝謝! –

1

Image對象有一個filename屬性。

from PIL import Image 


def foo_img(img_input): 
    print(img_input.filename) 

foo_img(Image.open('/path/to/some/img.img'))