From: Michael Tremer Date: Sat, 6 Jan 2024 15:27:31 +0000 (+0000) Subject: util: Optionally rotate JPEG images if coded into EXIF X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=6317802a1288a7aae20919abf4420bdd6615a5d1;p=ipfire.org.git util: Optionally rotate JPEG images if coded into EXIF Some pictures store the rotation of the picture in the EXIF data which we ignored in the past. Signed-off-by: Michael Tremer --- diff --git a/src/backend/util.py b/src/backend/util.py index 00747502..cddd677b 100644 --- a/src/backend/util.py +++ b/src/backend/util.py @@ -1,5 +1,6 @@ #!/usr/bin/python3 +import PIL.ExifTags import PIL.Image import PIL.ImageFilter import PIL.ImageOps @@ -218,6 +219,20 @@ def generate_thumbnail(data, size, square=False, **args): # Save image format format = image.format + # Fetch any EXIF data + exif = image._getexif() + + # Rotate the image + if exif: + for tag in PIL.ExifTags.TAGS: + if PIL.ExifTags.TAGS[tag] == "Orientation": + if exif[tag] == 3: + image = image.rotate(180, expand=True) + elif exif[tag] == 6: + image = image.rotate(270, expand=True) + elif exif[tag] == 8: + image = image.rotate( 90, expand=True) + # Remove any alpha-channels if image.format == "JPEG" and not image.mode == "RGB": # Make a white background