From 0348d6fbc87baa9e982885e5bdbb8d1433672c41 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Tue, 16 Jul 2024 19:26:40 +0100 Subject: [PATCH 1/2] fix: rotate images on source acquisition --- iiif/utils.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/iiif/utils.py b/iiif/utils.py index beb1b8f..9cab27a 100644 --- a/iiif/utils.py +++ b/iiif/utils.py @@ -14,7 +14,7 @@ import aiohttp import humanize -from PIL import Image +from PIL import Image, ImageOps from jpegtran import JPEGImage mimetypes.init() @@ -119,13 +119,8 @@ def convert_image(image_path: Path, target_path: Path, quality: int = 80, # given this is usually run in a separate process, make sure we have disabled bomb errors disable_bomb_errors() with Image.open(image_path) as image: - if image.format.lower() == 'jpeg': - exif = image.getexif() - # this is the orientation tag, remove it if it's there - exif.pop(0x0112, None) - image.info['exif'] = exif.tobytes() - target_path.parent.mkdir(parents=True, exist_ok=True) + image = ImageOps.exif_transpose(image) image = image.convert(mode='RGB') image.save(target_path, format='jpeg', quality=quality, subsampling=subsampling) From 7d06dc06ca1b5725e2baffc8b0bb201834b20938 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Sun, 21 Jul 2024 21:56:30 +0100 Subject: [PATCH 2/2] fix: make sure the image is loaded before rotating it based on exif If the first thing we do after lazily opening the image is call exif_transpose, we end up causing some issues with that functions logic. Specifically, TIFF images with a TIFF tag orientation will be double rotated because the exif_transpose function reads the TIFF tag orientation (in Pillow exif also includes these TIFF tags) before the image is loaded into memory, but once the image is loaded into memory the TIFF plugin will rotate the image based on the TIFF orientation tag before the exif_transpose function then also rotates it. To avoid this, do something else which will force the image to be loaded into memory before calling exif_transpose. Bit hacky but hey tis what it is. --- iiif/utils.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/iiif/utils.py b/iiif/utils.py index 9cab27a..fd486d9 100644 --- a/iiif/utils.py +++ b/iiif/utils.py @@ -120,8 +120,10 @@ def convert_image(image_path: Path, target_path: Path, quality: int = 80, disable_bomb_errors() with Image.open(image_path) as image: target_path.parent.mkdir(parents=True, exist_ok=True) - image = ImageOps.exif_transpose(image) + # do this before exif_transpose to ensure tiffs get loaded and oriented before + # we auto-orient based on exif image = image.convert(mode='RGB') + image = ImageOps.exif_transpose(image) image.save(target_path, format='jpeg', quality=quality, subsampling=subsampling)