You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python exif模块添加图片GPS元数据时遇RuntimeError问题求助

解决Python exif模块添加GPS时的RuntimeError问题

错误原因

这个错误是因为你的图片缺少IFD1(第二图像文件目录),它通常存储图片的缩略图信息。当前版本的exif模块在添加GPS元数据时,要求图片必须包含IFD1结构,否则无法写入GPS标签。

解决方案1:先用Pillow生成带IFD1的图片,再添加GPS

先使用Pillow库重新保存图片,自动生成IFD1,之后再用exif模块添加GPS信息:

from PIL import Image as PillowImage
from exif import Image

# 第一步:用Pillow重新保存图片,生成IFD1
with open("my_image.jpeg", "rb") as img_file:
    pillow_img = PillowImage.open(img_file)
    pillow_img.save("temp_image.jpeg")

# 第二步:用exif模块添加GPS信息
with open("temp_image.jpeg", "rb") as temp_file:
    exif_img = Image(temp_file)
    exif_img.gps_latitude = (37.0, 14, 3.6)
    exif_img.gps_latitude_ref = 'N'
    exif_img.gps_longitude = (115, 48, 23.99)
    exif_img.gps_longitude_ref = 'W'

    with open("my_newImage.jpeg", "wb") as new_file:
        new_file.write(exif_img.get_file())

解决方案2:换用piexif库直接添加GPS

如果不想依赖多个库,可以使用piexif库,它对无IFD1的图片兼容性更好:

import piexif
from PIL import Image

# 打开图片并读取现有EXIF数据
img = Image.open("my_image.jpeg")
exif_data = piexif.load(img.info.get("exif", b""))

# 构造GPS数据(格式为度分秒的整数元组)
gps_latitude = (37, 14, int(3.6 * 10000))
gps_longitude = (115, 48, int(23.99 * 10000))
exif_data["GPS"] = {
    piexif.GPSIFD.GPSLatitude: gps_latitude,
    piexif.GPSIFD.GPSLatitudeRef: b'N',
    piexif.GPSIFD.GPSLongitude: gps_longitude,
    piexif.GPSIFD.GPSLongitudeRef: b'W',
}

# 将修改后的EXIF写入新图片
exif_bytes = piexif.dump(exif_data)
img.save("my_newImage.jpeg", exif=exif_bytes)

说明

  • 方案1利用Pillow保存图片时自动生成IFD1的特性,让exif模块可以正常写入GPS;
  • 方案2的piexif库不需要依赖图片的IFD1结构,直接操作EXIF数据,更适合处理缺少基础EXIF结构的图片。

内容的提问来源于stack exchange,提问作者H S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:52:47