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.
pnginfo
parameter works to store the new data. As you indicate, I can retreave old data from the .text parameter of an open Image too. – Glantz