从Image PIL获取图像文件名

Der*_*den 5 python python-imaging-library python-2.7

是否有可能从Image对象中获取已经打开的Image的文件名?我检查了API,我能想到的最好的是PIL.Image.info,但是当我检查它时它似乎是空的.我还可以使用其他东西在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'))
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 11

我不知道这是否记录在任何地方,但只是dir在我打开的图像上使用显示了一个名为的属性filename:

>>> im = Image.open(r'c:\temp\temp.jpg')
>>> im.filename
'c:\\temp\\temp.jpg'
Run Code Online (Sandbox Code Playgroud)

遗憾的是,您不能保证该对象上的属性:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

您可以使用a try/except来捕获此问题AttributeError,或者您可以在尝试使用它之前测试该对象是否具有文件名:

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

c:\temp\temp.jpg
Run Code Online (Sandbox Code Playgroud)


das*_*chs 5

所述Image对象具有filename属性。

 from PIL import Image


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

 foo_img(Image.open('/path/to/some/img.img'))  
Run Code Online (Sandbox Code Playgroud)