Image dimensions do not consider EXIF rotation

Hi :waving_hand:,

I am searching for people who care about images in Django. Mainly about: #34035 (ImageField doesn't consider EXIF rotation when storing width and height) – Django

The ticket was previously closed, since changing one for the other would result in a breaking change. I’d still argue that it’s a bug, but I sense that that’s a discussion I can’t win.

My proposal would be to at least provide the option to include the EXIF rotation.

At the very least, I’d propose to add a note to the documentation. I have been maintaining django-stdimage and now django-pictures for 14 years without knowing about this limitation. But maybe it was just me… you never know…

Cheers!
Joe

2 Likes

Hi @codingjoe ,
Thank you for raising that ticket.
We had same “bug” in our system which we were not aware of until we found out on production by our users.

So we wrote out custom mixin on top of that like next:

class ImageDimensionUpdateMixin:
    """
    Updates model dimensions from uploaded JPEG image with EXIF orientation fix.
    """

    def pre_save(self, model_instance, add):
        file = super().pre_save(model_instance, add)
        if file and file.name:
            with file.storage.open(file.name, 'rb') as f, PILImage.open(f) as img:
                if img.format and img.format.lower() == 'jpeg':
                    # Correct the orientation based on EXIF data
                    transposed_img = ImageOps.exif_transpose(img)
                    # Update the model instance's width and height fields with the image dimensions
                    setattr(model_instance, self.width_field, transposed_img.width)
                    setattr(model_instance, self.height_field, transposed_img.height)
        return file

We use it with combination of improved version of ImageField from Matthias → GitHub - feincms/django-imagefield: You should probably use this image field instead of Django's built-in models.ImageField. · GitHub

1 Like

Thanks. Good to know it wasn’t just me.

I know how to fix it in django-pictures, but I’d rather patch this upstream.

1 Like