I'm trying to get the EXIF tags of an JPG image. To do this, I'm using piexif
module.
The problem is that I get an error - KeyError
, saying this:
Traceback (most recent call last):
File "D:/PythonProjects/IMGDateByNameRecovery/recovery.py", line 98, in selectImages
self.setExifTag(file_str)
File "D:/PythonProjects/IMGDateByNameRecovery/recovery.py", line 102, in setExifTag
exif = piexif.load(img.info["Exif"])
KeyError: 'Exif'
I've did everything as in the docs, here on some questions StackOverflow and on pypi website. Everything the same. My code:
img = Image.open(file)
exif_dict = piexif.load(img.info["exif"])
altitude = exif_dict['GPS'][piexif.GPSIFD.GPSAltitude]
print(altitude)
How do I read the image's EXIF tags then? Am I doing it wrong? Please, I'm so clueless. This is such a weird error.
Pillow only adds the exif
key to the Image.info
if EXIF data exists. So if the images has no EXIF data your script will return the error because the key does not exist.
You can see what image formats support the info["exif"]
data in the Image file formats documentation.
You could do something like this...
img = Image.open(file)
exif_dict = img.info.get("exif") # returns None if exif key does not exist
if exif_dict:
exif_data = piexif.load(exif_dict)
altitude = exif_data['GPS'][piexif.GPSIFD.GPSAltitude]
print(altitude)
else:
pass
# Do something else when there is no EXIF data on the image.
Using mydict.get("key")
will return a value of None
if the key does not exist where as mydict["key"]
will throw a KeyError
.