Get Image Filename from Image PIL
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
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
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'))