Skip to content

Instantly share code, notes, and snippets.

@Russell-Tran
Last active April 17, 2024 06:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Russell-Tran/8817fec10991f04ca4b098317485690c to your computer and use it in GitHub Desktop.
Save Russell-Tran/8817fec10991f04ca4b098317485690c to your computer and use it in GitHub Desktop.
Store custom data in .tif EXIF metadata using Python
from PIL import Image
# Use the UserComment field, since manufacturers et al. leave it empty
# https://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/usercomment.html
EXIF_USERCOMMENT = 37510
def write_exif(src_path, dst_path, json_dict):
"""Write json (dictionary)
"""
write_exif_string(src_path, dst_path, json.dumps(json_dict))
def write_exif_string(src_path, dst_path, string):
"""Write a string
"""
image = Image.open(src_path)
image.tag[EXIF_USERCOMMENT] = string
image.save(dst_path, tiffinfo=image.tag)
def read_exif(path):
"""Returns json (dictionary)
"""
return json.loads(read_exif_string(path))
def read_exif_string(path):
"""Returns a string
"""
with Image.open(path) as image:
return image.tag[EXIF_USERCOMMENT][0]
@Russell-Tran
Copy link
Author

Example:

    path = "/path/to/photo.tif"

    data = {
        "fruit" : "pineapple"
    }

    write_exif(path, path, data)
    print(read_exif(path)["fruit"])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment