From 7a60f23ebf81dcc1e7b952d974ab0bd8aea24a26 Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Thu, 23 Jun 2022 10:55:32 -0700 Subject: [PATCH] Add function get_exif_datetime. --- voussoirkit/imagetools.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/voussoirkit/imagetools.py b/voussoirkit/imagetools.py index f941d40..a98cfd5 100644 --- a/voussoirkit/imagetools.py +++ b/voussoirkit/imagetools.py @@ -1,8 +1,11 @@ import copy +import datetime import io import PIL.ExifTags import PIL.Image +from voussoirkit import pathclass + ORIENTATION_KEY = None for (ORIENTATION_KEY, val) in PIL.ExifTags.TAGS.items(): if val == 'Orientation': @@ -59,6 +62,29 @@ def fit_into_bounds( return (new_width, new_height) +def get_exif_datetime(image) -> datetime.datetime: + # Thanks Payne + # https://stackoverflow.com/a/4765242 + if isinstance(image, pathclass.Path): + image = PIL.Image.open(image.absolute_path) + elif isinstance(image, str): + image = PIL.Image.open(image) + + exif = image.getexif() + if not exif: + return + + exif = { + PIL.ExifTags.TAGS[key]: value + for (key, value) in exif.items() + if key in PIL.ExifTags.TAGS + } + exif_date = exif.get('DateTimeOriginal') or exif.get('DateTime') or exif.get('DateTimeDigitized') + if not exif_date: + return + + return datetime.datetime.strptime(exif_date, '%Y:%m:%d %H:%M:%S') + def pad_to_square(image, background_color=None) -> PIL.Image: ''' If the given image is not already square, return a new, square image with