从Image PIL获取图像文件名

时间:2017-07-13 17:42:29

标签: python python-2.7 python-imaging-library

是否可以从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'))

3 个答案:

答案 0 :(得分:8)

我不知道这是否记录在任何地方,但只是在我打开的图片上使用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

答案 1 :(得分:2)

Image对象具有filename属性。

 from PIL import Image


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

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

答案 2 :(得分:0)

另一种方法是使用初始文件位置:

def getImageName(file_location):
    filename = file_location.split('/')[-1]
    location = file_location.split('/')[0:-1]
    filename = filename.split('.')
    filename[0] += "_resized"
    filename = '.'.join(filename)
    new_path = '/'.join(location) + '/' + filename
    return new_path