Skip to content

Instantly share code, notes, and snippets.

@kaczmarj
Created April 29, 2021 19:13
Show Gist options
  • Save kaczmarj/5897f9f5177c444f575145f9614f609c to your computer and use it in GitHub Desktop.
Save kaczmarj/5897f9f5177c444f575145f9614f609c to your computer and use it in GitHub Desktop.
def to_png_with_metadata(img, path, **meta_kwds):
"""Write a PIL image to PNG with associated metadata.
Parameters
----------
img : PIL.Image.Image
Image to write.
path : str, pathlib.Path
Save the image to this path. The extension '.png' is added
if it is not present.
**meta_kwds
Key=value pairs to write to the PNG file.
Returns
-------
None
Example
-------
>>> import PIL.Image
>>> to_png_with_metadata(image, "foo.png", name="bob")
>>> saved_img = PIL.Image.open("foo.png")
>>> saved_img.text
{"name": "bob"}
"""
from pathlib import Path
from PIL.PngImagePlugin import PngInfo
pnginfo = PngInfo()
for key, value in meta_kwds.items():
pnginfo.add_text(key, str(value))
path = Path(path).with_suffix(".png")
img.save(path, format="png", pnginfo=pnginfo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment