About Normalizing Image Rotation

Some images come with Orientation tag in the meta data from a camera. When these images are modified with Pillow, they are shown as rotated on a side. Here is a utility function to normalize rotation and remove the Orientation tag:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def normalize_rotation(input_file_path, output_file_path=None):
    from django.core.files.storage import default_storage
    from PIL import Image, ImageOps

    if not output_file_path:
        output_file_path = input_file_path

    fpr = default_storage.open(input_file_path)
    with Image.open(fpr) as input_image:
        output_image = ImageOps.exif_transpose(input_image)

        with default_storage.open(output_file_path, "wb+") as fpw:
            output_image.save(
                fpw,
                format=input_image.format,
                icc_profile=output_image.info.get("icc_profile"),
                quality=95,
            )

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Python 3 Pillow