我正在尝试获取JPG图像的EXIF标签。为此,我正在使用piexif
模块。问题是我得到一个错误-KeyError
,这是这样的:
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'
我已经完成了文档中的所有操作,这里是有关StackOverflow和pypi网站的一些问题。一切都一样。我的代码:
img = Image.open(file)
exif_dict = piexif.load(img.info["exif"])
altitude = exif_dict['GPS'][piexif.GPSIFD.GPSAltitude]
print(altitude)
然后,如何读取图像的EXIF标签?我做错了吗?拜托,我真笨。这是一个很奇怪的错误。
枕头仅在存在EXIF数据的情况下才将exif
键添加到Image.info
。因此,如果图像没有EXIF数据,则脚本将返回错误,因为密钥不存在。
您可以在info["exif"]
中看到哪些图像格式支持Image file formats documentation数据。
您可以做这样的事情...
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.
如果键不存在,则使用mydict.get("key")
将返回None
的值,因为mydict["key"]
将返回KeyError
。