Rotating an image with orientation specified in EXIF using Python without PIL including the thumbnail

后端 未结 6 1269
太阳男子
太阳男子 2020-12-02 09:10

I have the following scenario:

  • I am sending an image from iPhone along with the EXIF information to my Pyhon socket server.
  • I need the image to be pro
6条回答
  •  执笔经年
    2020-12-02 09:56

    Since this is the top answer for "python exif rotate" I'd like to add an addendum in case you only need the rotation value and not have PIL rotate the image - in my case I used QPixmap to rotate the image on a QGraphicsView, so I only needed the angle for the QPixmap transformation.
    The answer above using PIL to get exif is rather slow. In my test it took 6x the time as the piexif library did (6 ms vs 1 ms) because creating/opening the PIL.Image takes a lot of time. So I'd recommend using piexif in this case.

    import piexif
    
    def get_exif_rotation_angle(picture)
    
        exif_dict = piexif.load(picture)
        if piexif.ImageIFD.Orientation in exif_dict["0th"]:
            orientation = exif_dict["0th"][piexif.ImageIFD.Orientation]
            if orientation == 3:
                return 180
            elif orientation == 6:
                return 90
            elif orientation == 8:
                return 270
            else:
                return None
        else:
            return None
    

    picture can be file path or bytes object.

    Ref: https://piexif.readthedocs.io/en/latest/sample.html#rotate-image-by-exif-orientation

提交回复
热议问题