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

2024-09-22 16:22:52 发布

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

我使用来自PngImagePlugin模块的PngImageFilePngInfo将元数据存储在枕头中,方法是遵循Jonathan Feenstra在回答中给出的代码:How do I save custom information to a PNG Image file in Python?

代码是:

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图像上的元数据


Tags: 数据代码textaddstringpngsavemetadata
1条回答
网友
1楼 · 发布于 2024-09-22 16:22:52

在复制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
                    

相关问题 更多 >