lehins / django-smartfields

Django Model Fields that are smart.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ImageProcessor EXIF Orientation tag

lehins opened this issue · comments

Need to implement automatic orientation adjustment whenever Orientation EXIF tag is present on JPEG and TIFF formats.

Apparently PIL library behaves wrong with images that has EXIF tags.
Details:
Rotating an image with orientation specified in EXIF using Python without PIL including the thumbnail

Possible workaround:
PIL Library introduced PIL.ImageOps.exif_transpose(image)->Image method that deals with it properly.
The least invasive workaround is to add such method call somewhere in ImageProcessor:

from PIL import ImageOps

class CustomImageProcessor(ImageProcessor):
    def get_image(self, stream, **kwargs):
        image = super(CustomImageProcessor, self).get_image(stream, **kwargs)
        return ImageOps.exif_transpose(image)

and then, use CustomImageProcessor class in Model

class ProductImage(Base):
    product = models.ForeignKey(
        "product.Product",
        on_delete=models.CASCADE,
    )
    file = fields.ImageField(
        _("Image"),
        upload_to="product",
        dependencies=[
            FileDependency(
                attname="file_original",
                processor=CustomImageProcessor(
                    format="JPEG", scale={"max_width": 1024, "max_height": 768}
                ),
            ),
        ],
    )
    file_original = fields.ImageField(
        _("Image original"), upload_to="original", blank=True, null=True
    )

This workaround works for me.