Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Image Filename from Image PIL

Is it possible to get the filename of an Image I have already opened from an Image object? I checked the API, and the best I could come up with was the PIL.Image.info, but that appears to be empty when I check it. Is there something else I can use to get this info in the PIL Image library?

(Yes, I realize I can pass the filename into the function. I am looking for another way to do this.)

i.e.

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'))
like image 908
Derek Halden Avatar asked Jul 13 '17 17:07

Derek Halden


People also ask

How can I get image name in PIL?

Image. filename – This function is used to get the file name or the path of the image. If the image is not opened using 'open()' function it returns the null string.

How do I find the filename of an image?

You can view the filename of any image on the internet — here's how. Right click on the image and select “Inspect.” The image HTML should come up — look for the src tag — focus on the unique end slug (highlighted below.) That's the image filename.


1 Answers

I don't know if this is documented anywhere, but simply using dir on an image I opened showed an attribute called filename:

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

Unfortunately you can't guarantee that attribute will be on the object:

>>> 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'

You can get around this problem using a try/except to catch the AttributeError, or you can test to see if the object has a filename before you try to use it:

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

c:\temp\temp.jpg
like image 57
Mark Ransom Avatar answered Oct 17 '22 11:10

Mark Ransom