尝试获取图像的EXIF标签时出错 [英] Error while trying to get the EXIF tags of the image

查看:199
本文介绍了尝试获取图像的EXIF标签时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取JPG图像的EXIF标签.为此,我正在使用piexif模块.
问题是我得到一个错误-KeyError,这样说:

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'

我已经完成了文档中的所有操作,这里是有关StackOverflow和pypi网站的一些问题.一切都一样.我的代码:

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)

那我该如何读取图像的EXIF标签?我做错了吗? 拜托,我太笨了.这是一个很奇怪的错误.

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.

推荐答案

如果存在EXIF数据,则枕头仅将exif键添加到Image.info.因此,如果图像没有EXIF数据,则脚本将返回错误,因为该键不存在.

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

如果键不存在,则使用mydict.get("key")会返回None的值,而mydict["key"]会抛出KeyError.

Using mydict.get("key") will return a value of None if the key does not exist where as mydict["key"] will throw a KeyError.

这篇关于尝试获取图像的EXIF标签时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆