如何删除之前添加的 PNG 图像文件中的自定义信息?

How do I remove custom information in a PNG image file that I've previously added?

我使用 PngImagePlugin 模块中的 PngImageFilePngInfo 将元数据存储在 Pillow 中,方法是遵循 Jonathan Feenstra 在这个答案中的代码:

密码是:

from PIL.PngImagePlugin import PngImageFile, PngInfo
targetImage = PngImageFile("pathToImage.png")
metadata = PngInfo()
metadata.add_text("MyNewString", "A string")
metadata.add_text("MyNewInt", str(1234))
targetImage.save("NewPath.png", pnginfo=metadata)
targetImage = PngImageFile("NewPath.png")
print(targetImage.text)
>>> {'MyNewString': 'A string', 'MyNewInt': '1234'}

现在,我想删除之前添加到图像的附加元数据,即文本字符串。如何删除之前添加的 PNG 图片上的元数据?

复制 targetImage 时,text 属性似乎没有保留。因此,如果您在运行时需要没有附加元数据的图像,只需复制一份即可。

另一方面,您可以再次保存 targetImage,但不使用 pnginfo 属性。打开后,text 属性存在,但为空。也许,在 save 调用中,pnginfo=None 被隐式设置了!?

下面是一些演示代码:

from PIL.PngImagePlugin import PngImageFile, PngInfo


def print_text(image):
    try:
        print(image.text)
    except AttributeError:
        print('No text attribute available.')


targetImage = PngImageFile('path/to/your/image.png')

metadata = PngInfo()
metadata.add_text('MyNewString', 'A string')
metadata.add_text('MyNewInt', str(1234))

# Saving using proper pnginfo attribute
targetImage.save('NewPath.png', pnginfo=metadata)

# On opening, text attribute is available, and contains proper data
newPath = PngImageFile('NewPath.png')
print_text(newPath)
# {'MyNewString': 'A string', 'MyNewInt': '1234'}

# Saving without proper pnginfo attribute (implicit pnginfo=None?)
newPath.save('NewPath2.png')

# On opening, text attribute is available, but empty
newPath2 = PngImageFile('NewPath2.png')
print_text(newPath2)
# {}

# On copying, text attribute is not available at all
copyTarget = targetImage.copy()
print_text(copyTarget)
# No text attribute available.
----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.1
Pillow:        8.2.0
----------------------------------------