使用pyexiv2将EXIF信息从一个映像复制并写入另一个映像

2024-10-01 13:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pyexiv2将映像文件的EXIF信息复制到同一映像的已调整大小的版本。在寻找解决方案时,我在Stack Overflow上偶然发现了一篇帖子。函数中使用的api似乎已过时,无法在最新版本中使用。基于最新的文档,我创建了一个这样的函数

def get_exif(file):
    """
    Retrieves EXIF information from a image
    """
    ret = {}
    metadata = pyexiv2.ImageMetadata(str(file))
    metadata.read()
    info = metadata.exif_keys
    for key in info:
        data = metadata[key]
        ret[key] = data.raw_value
    return ret

def write_exif(originFile, destinationFile, **kwargs):
    """
    This function would write an exif information of an image file to another image file
    """

    exifInformation = get_exif(originFile)
    metadata = pyexiv2.ImageMetadata(str(destinationFile))
    for key, value in exifInformation.iteritems():
        metadata[key] = value

    copyrightName = kwargs.get('copyright', None)
    if copyrightName != None:
        metadata['Exif.Image.Copyright'] = copyrightName

    try:
        metadata.write()
    except:
        return False
    else:
        return True

但这最终是一个错误

Python argument types in _ExifTag._setParentImage(_ExifTag, NoneType) did not match C++ signature: _setParentImage(exiv2wrapper::ExifTag {lvalue}, exiv2wrapper::Image {lvalue})

我现在不知道哪里出了问题。有人能帮帮我吗?谢谢

编辑

基于@unutbu的建议,我对data.raw_值在get_exif()方法中数据.值但仍然面临着同样的问题。我正在粘贴有关此错误的详细信息:

^{pr2}$

Tags: keyinimagedatagetreturnvaluefile
2条回答

在PyExv2 0.3版本中,@user2431382的解决方案将不允许将EXIF标记写入目标_文件!=源_文件。以下版本适用于我:

m1 = pyexiv2.ImageMetadata( source_filename )
m1.read()
# modify tags ...
# m1['Exif.Image.Key'] = pyexiv2.ExifTag('Exif.Image.Key', 'value')
m1.modified = True # not sure what this is good for
m2 = pyexiv2.metadata.ImageMetadata( destination_filename )
m2.read() # yes, we need to read the old stuff before we can overwrite it
m1.copy( m2 )
m2.write()

而不是metadata['Exif.Image.Copyright'] = copyrightName

你必须使用语法作为

metadata['Exif.Image.Copyright']  = pyexiv2.ExifTag('Exif.Image.Copyright', copyrightName)

注意:copyrightName值应为字符串“Exif.Image.版权所有““

完整的例子

^{pr2}$

希望这对你有帮助

相关问题 更多 >