python - 获取 "' NoneType' 对象没有属性 'items'“PIL 库错误

标签 python python-3.x python-imaging-library

代码:

#!/usr/bin/python3

from PIL import Image, ExifTags

img = Image.open("/root/Bilder/sysPics/schwarz-weiß-Karte.jpg")

for i, j in img._getexif().items():
    if i in ExifTags.TAGS:
        print(ExifTags.TAGS[i] + " - " + str(j))

错误:

Traceback (most recent call last):
  File "python-tool.py", line 7, in <module>
    for i, j in img._getexif().items():
AttributeError: 'NoneType' object has no attribute 'items'

谁能帮帮我?我从未使用过 PIL 库,但我看到了一个教程, 此 .items() 方法在其中起作用:

https://www.youtube.com/watch?v=-PiR5SX4Mxo&list=PLNmsVeXQZj7onbtIXvxZTzeKGnzI6NFp_&index=8

他的代码和我的没有区别,我不敢相信他们在最后的补丁中切断了 .items() 方法。

最佳答案

第一,您不应该依赖内部函数,例如 _get_exif()因为它们的实现可以随时更改,而且它们通常不供公众使用。 (参见 PEP8 命名约定中的 _single_leading_underscore )。

第二,您应该考虑到并非所有图像都有 EXIF 数据。尝试获取 EXIF 数据可能会 None .所以它不是 .items()这就是问题的方法,而是你的 _get_exif()返回 None .您的代码没有针对这种情况的处理,您总是假设 _get_exif()返回 dict .

现在,为了解决您的问题,对于 Python3.x(我有 Python3.6.8)和 PIL(安装为 Pillow,Pillow==6.0.0),Image对象现在提供公共(public) getexif()您可以使用的方法。返回类型是 None如果图像没有 EXIF 数据或 <class 'PIL.Image.Exif'> .

from PIL import Image, ExifTags

img = Image.open("sample.jpg")
print(dir(img))
# [... 'getexif' ...]

img_exif = img.getexif()
if img_exif:
    print(type(img_exif))
    # <class 'PIL.Image.Exif'>
    print(dict(img_exif))
    # { .. 271: 'FUJIFILM', 305: 'Adobe Photoshop Lightroom 6.14 (Macintosh)', }

    img_exif_dict = dict(img_exif)
    for key, val in img_exif_dict.items():
        if key in ExifTags.TAGS:
            print(ExifTags.TAGS[key] + " - " + str(val))
else:
    print("Sorry, image has no exif data.")

关于python - 获取 "' NoneType' 对象没有属性 'items'“PIL 库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560211/

相关文章:

python - PIL : how to draw € on an image with draw. 文本?

python - 如何在 django-filter 中包含列表理解结果?

java - 在 Java TensorFlow 1.15 中使用 Python 构建的 TensorFlow 2.1.0 模型 |图表中没有名为 [input] 的操作

python - 抽象季节/节目/剧集数据的最佳方式

sockets - Python 3 中的 Websocket 实现

python - 使用 numpy 快速迭代像素

python - 在python中将像year biyear这样的字符串转换为整数

python-3.x - 如何使用 boto3(或其他 Python)列出 _RequesterPays_ S3 存储桶的内容?

python - 使用 Python 3 将一个文件的内容复制到另一个文件中

python - 属性错误: 'Image' object has no attribute 'thumbnail'