0

I'm doing an API, which gets images from phone application. Images contain EXIF data, and some of these images have an orientation tag (according to: PIL thumbnail is rotating my image?). Currently I solve problem with using imagemagick/morgify in commandline. But I'm wondering whether it is possible (or make sense) to do auto-orient with PIL/Pillow after receiving data in DRF view.

--edit--

It looks like, I have to use save and delete hooks from http://www.django-rest-framework.org/api-guide/generic-views/

Community
  • 1
  • 1
404pio
  • 1,080
  • 1
  • 12
  • 32

1 Answers1

1

Ok, so the code is (autorotation code copied from PIL thumbnail is rotating my image?):

from PIL import Image, ExifTags


def autorotate(path):
    """ This function autorotates a picture """
    image = Image.open(path)
    if hasattr(image, '_getexif'):  # only present in JPEGs
        orientation = None
        for orientation in ExifTags.TAGS.keys():
            if ExifTags.TAGS[orientation] == 'Orientation':
                break
        e = image._getexif()  # returns None if no EXIF data
        if e is not None:
            exif = dict(e.items())
            orientation = exif[orientation]

            if orientation == 3:
                image = image.transpose(Image.ROTATE_180)
            elif orientation == 6:
                image = image.transpose(Image.ROTATE_270)
            elif orientation == 8:
                image = image.transpose(Image.ROTATE_90)
            image.save(path)

class ReceivedDataList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = UserFilter

    def perform_create(self, serializer):
        instance = serializer.save()
        autorotate(instance.photo.file.name)
Community
  • 1
  • 1
404pio
  • 1,080
  • 1
  • 12
  • 32