【问题标题】:How do I remove custom information in a PNG image file that I've previously added?如何删除之前添加的 PNG 图像文件中的自定义信息?
【发布时间】:2021-08-29 23:45:47
【问题描述】:

我使用 PngImagePlugin 模块中的 PngImageFilePngInfo 将元数据存储在 Pillow 中,方法是遵循 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 图片上的元数据?

【问题讨论】:

    标签: python text python-imaging-library png metadata


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多