使用 Python 和 Piexif 将 EXIF GPS 数据添加到 .jpg 文件

问题描述 投票:0回答:1

我正在尝试编写一个脚本,使用 Python 将 EXIF GPS 数据添加到图像中。运行以下脚本时,我收到从

piexif.dump()
返回的错误,如下所示:

(venv) C:\projects\geo-photo>python test2.py
Traceback (most recent call last):
  File "C:\projects\geo-photo\test2.py", line 31, in <module>
    add_geolocation(image_path, latitude, longitude)
  File "C:\projects\geo-photo\test2.py", line 21, in add_geolocation
    exif_bytes = piexif.dump(exif_dict)
                 ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\projects\geo-photo\venv\Lib\site-packages\piexif\_dump.py", line 74, in dump
    gps_set = _dict_to_bytes(gps_ifd, "GPS", zeroth_length + exif_length)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\projects\geo-photo\venv\Lib\site-packages\piexif\_dump.py", line 335, in _dict_to_bytes
    length_str, value_str, four_bytes_over = _value_to_bytes(raw_value,
                                             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\projects\geo-photo\venv\Lib\site-packages\piexif\_dump.py", line 244, in _value_to_bytes
    new_value += (struct.pack(">L", num) +
struct.error: argument out of range

有人知道为什么会发生这种情况吗?以下是完整的脚本。任何帮助表示赞赏。

import piexif

def add_geolocation(image_path, latitude, longitude):
    exif_dict = piexif.load(image_path)

    # Convert latitude and longitude to degrees, minutes, seconds format
    def deg_to_dms(deg):
        d = int(deg)
        m = int((deg - d) * 60)
        s = int(((deg - d) * 60 - m) * 60)
        return ((d, 1), (m, 1), (s, 1))

    lat_dms = deg_to_dms(latitude)
    lon_dms = deg_to_dms(longitude)

    exif_dict["GPS"][piexif.GPSIFD.GPSLatitude] = lat_dms
    exif_dict["GPS"][piexif.GPSIFD.GPSLongitude] = lon_dms
    exif_dict["GPS"][piexif.GPSIFD.GPSLatitudeRef] = 'N' if latitude >= 0 else 'S'
    exif_dict["GPS"][piexif.GPSIFD.GPSLongitudeRef] = 'E' if longitude >= 0 else 'W'

    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, image_path)

    print("Geolocation data added to", image_path)

# Example usage
latitude = 34.0522  # Example latitude coordinates
longitude = -118.2437  # Example longitude coordinates
image_path = 'test.jpg'  # Path to your image

add_geolocation(image_path, latitude, longitude)
python exif piexif
1个回答
0
投票

看起来问题的根源是负经度/纬度值,因为只有负值才会导致此错误。
here的讨论中您可以看到负值在添加到 exif 之前已转换为正值。还发现这个例子将负值转换为正值,同时保持右半/半球 - N/S或E/W。我不知道为什么该模块不使用负值 - 一些 EXIF 阅读器也会读取 N/S E/W 值就像这个,而其他人会忽略它 - 就像你使用的 Windows 内置阅读器一样右键单击图像 -> 属性 -> 详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.