Last active
April 17, 2024 06:32
-
-
Save Russell-Tran/8817fec10991f04ca4b098317485690c to your computer and use it in GitHub Desktop.
Store custom data in .tif EXIF metadata using Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: