Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save custom information to a PNG Image file in Python?

I would like to open a PNG image in Python, add some custom data to it, save the image file and at a later time open it again to retrieve the data. I am working in Python 3.7. I would prefer to use the PNG image format but could move to another format if there was little other option.

I have read lots of outdated answers and articles from before the PNG standard was updated to allow custom data to be stored in it. I would like an answer for what is available today (October 2019) or would, of course, accept updated answers in the future if something helpful is enabled. It really is hard to search for this sort of specific issue as "save", "png", "python", "info" are all quite generic terms.


I can retrieve some data using Pillow (6.2.0 at present). What I cannot work out is how to store more than the exif data to a png.

from PIL import image
targetImage = Image.open("pathToImage.png")
targetImage.info["MyNewString"] = "A string"
targetImage.info["MyNewInt"] = 1234
targetImage.save("NewPath.png")

The above loses the information when I save. I have seen some documentation for using targetImage.save("NewPath.png", exif=exif_bytes) but that only works with exif formatted data. I looked at the piexif and piexif2 packages but they either only support JPEG or will not allow custom data.

I do not mind if the information is stored as iTXt, tEXt or zTXt chunks in the PNG. See https://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_PNG_files for an explanation of the formats.


I am quite new to Python so I apologise if I have missed something obvious in the documentation that a more practised coder would recognise. I really would like to not re-invent the wheel if a solution already exists.

like image 896
TafT Avatar asked Oct 15 '19 16:10

TafT


1 Answers

You can store metadata in Pillow using PngImagePlugin.PngInfo like this:

from PIL import Image
from PIL.PngImagePlugin import PngInfo

targetImage = Image.open("pathToImage.png")

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

targetImage.save("NewPath.png", pnginfo=metadata)
targetImage = Image.open("NewPath.png")

print(targetImage.text)

>>> {'MyNewString': 'A string', 'MyNewInt': '1234'}

In this example I use tEXt, but you can also save it as iTXt using add_itxt.

like image 118
Jonathan Feenstra Avatar answered Oct 07 '22 20:10

Jonathan Feenstra