Python使用Pillow库无法读取图片全部EXIF元数据标签如何解决
问题原因
你使用img.getexif()仅能读取到5个标签,是因为该方法默认只返回最顶层的0th IFD(图像文件目录)标签,其余拍摄参数(光圈、曝光、焦距等)都存储在ExifOffset指向的Exif Sub IFD子目录中,需要单独读取该子目录的内容。
读取全量EXIF标签的实现代码(基于原生Pillow)
from PIL import Image from PIL.ExifTags import TAGS, GPSTAGS def get_full_exif(image_path): exif_dict = {} with Image.open(image_path) as img: base_exif = img.getexif() # 读取顶层0th IFD标签 for tag_id, value in base_exif.items(): tag_name = TAGS.get(tag_id, str(tag_id)) if isinstance(value, bytes): try: value = value.decode() except: pass exif_dict[tag_name] = value # 读取Exif Sub IFD标签(缺失的拍摄参数都在该目录下) exif_sub_ifd = base_exif.get_ifd(0x8769) for tag_id, value in exif_sub_ifd.items(): tag_name = TAGS.get(tag_id, str(tag_id)) if isinstance(value, bytes): try: value = value.decode() except: pass exif_dict[tag_name] = value # 可选:读取GPS相关标签 gps_ifd = base_exif.get_ifd(0x8825) for tag_id, value in gps_ifd.items(): tag_name = GPSTAGS.get(tag_id, str(tag_id)) if isinstance(value, bytes): try: value = value.decode() except: pass exif_dict[tag_name] = value return exif_dict # 调用示例 full_exif = get_full_exif('IMG_20191210_114027.jpg') # 打印所有标签 for k, v in full_exif.items(): print(f"{k:25}: {v}")
标签单独存储的实现
推荐直接使用返回的字典存储所有标签,取值时直接通过键访问即可,还可以避免标签不存在时报错:
# 按需提取标签为单独变量 make = full_exif.get('Make', '未知') model = full_exif.get('Model', '未知') exposure_time = full_exif.get('ExposureTime', '未知') f_number = full_exif.get('FNumber', '未知') # 其余标签以此类推
如果需要自动生成所有标签对应的变量,可以使用如下方法(不推荐,容易出现变量名冲突):
for tag, value in full_exif.items(): var_name = tag.replace(' ', '_') globals()[var_name] = value # 之后可直接通过标签名访问,比如print(Model)、print(DateTimeOriginal)
内容的提问来源于stack exchange,提问作者Ibraheem Alibraheem
相关产品推荐
相关产品推荐

