Use exifread for paths, pil for existing image objects.

Instead of using pil all the time.
master
voussoir 2022-08-03 18:43:17 -07:00
parent 720a2bebcf
commit 353cba7dfd
No known key found for this signature in database
GPG Key ID: 5F7554F8C26DACCB
1 changed files with 30 additions and 9 deletions

View File

@ -9,6 +9,8 @@ import re
from voussoirkit import pathclass from voussoirkit import pathclass
_exifread = exifread
ORIENTATION_KEY = None ORIENTATION_KEY = None
for (ORIENTATION_KEY, val) in PIL.ExifTags.TAGS.items(): for (ORIENTATION_KEY, val) in PIL.ExifTags.TAGS.items():
if val == 'Orientation': if val == 'Orientation':
@ -65,14 +67,7 @@ def fit_into_bounds(
return (new_width, new_height) return (new_width, new_height)
def get_exif_datetime(image) -> datetime.datetime: def _get_exif_datetime_pil(image):
# 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() exif = image.getexif()
if not exif: if not exif:
return return
@ -87,6 +82,32 @@ def get_exif_datetime(image) -> datetime.datetime:
if not exif_date: if not exif_date:
return None return None
return exif_date
def _get_exif_datetime_exifread(path):
path = pathclass.Path(path)
exif = _exifread.process_file(path.open('rb'))
exif_date = exif.get('EXIF DateTimeOriginal') or exif.get('Image DateTime') or exif.get('EXIF DateTimeDigitized')
if not exif_date:
return None
exif_date = exif_date.values
return exif_date
def get_exif_datetime(image) -> datetime.datetime:
# Thanks Payne
# https://stackoverflow.com/a/4765242
if isinstance(image, (str, pathclass.Path)):
exif_date = _get_exif_datetime_exifread(image)
elif isinstance(image, PIL.Image.Image):
exif_date = _get_exif_datetime_pil(image)
if not exif_date:
return None
if exif_date.startswith('0000:'):
return None
exif_date = re.sub(r'(\d\d\d\d):(\d\d):(\d\d)', r'\1-\2-\3', exif_date) exif_date = re.sub(r'(\d\d\d\d):(\d\d):(\d\d)', r'\1-\2-\3', exif_date)
return dateutil.parser.parse(exif_date) return dateutil.parser.parse(exif_date)
@ -100,7 +121,7 @@ def exifread(path) -> dict:
elif isinstance(path, str): elif isinstance(path, str):
handle = open(path, 'rb') handle = open(path, 'rb')
return exifread.process_file(handle) return _exifread.process_file(handle)
def pad_to_square(image, background_color=None) -> PIL.Image: def pad_to_square(image, background_color=None) -> PIL.Image:
''' '''