1

I store metadata in Pillow using PngImageFile and PngInfo from the PngImagePlugin module by following the code from Jonathan Feenstra in this answer: How do I save custom information to a PNG Image file in Python?

The code is :

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'}

Now, I want to remove the additional metadata that was previously added to the image which is the text string. How do I remove the metadata on the previously added PNG image?

HansHirse
  • 18,010
  • 10
  • 38
  • 67
Rizkii
  • 25
  • 4

1 Answers1

2

It seems the text attribute isn't preserved when doing a copy of targetImage. So, if you need the image without the additional metadata at runtime, just make a copy.

On the other hand, you can save targetImage again, but without using the pnginfo attribute. After opening, the text attribute is present, but empty. Maybe, in the save call, pnginfo=None is implicitly set!?

Here's some code for demonstration:

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
----------------------------------------
HansHirse
  • 18,010
  • 10
  • 38
  • 67