Reputation: 2323
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'))
Upvotes: 21
Views: 52435
Reputation: 432
Another way how I did it is by using the initial file location:
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
Upvotes: 2
Reputation: 719
The Image
object has a filename
attribute.
from PIL import Image
def foo_img(img_input):
print(img_input.filename)
foo_img(Image.open('/path/to/some/img.img'))
Upvotes: 8
Reputation: 308158
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
Upvotes: 32