简体   繁体   中英

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.

You can store metadata in Pillow using PngImageFile and PngInfo from the PngImagePlugin module like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM