• Python 使用PIL读取图像自动旋转exif信息


    Python 使用PIL读取图像自动旋转exif信息

    今天遇到一个图片存在自动旋转的问题,也就是图像exif 字段不为空的问题,写个简单脚本记录一下。

    Python3实现:

    import traceback
    import PIL
    from PIL import Image, ImageOps
    
    
    def image_transpose(img_path):
        """
        :param img_path: 图像路径
        :return: pil对象
        """
    
        try:
            # print(PIL.ExifTags.TAGS)  # 获取exif 所以标签 是个字典
    
            image = Image.open(img_path)  # 读取图像
            exif_data = image._getexif()  # 获取exif信息
    
            if exif_data and exif_data.get(274):
                orientation = exif_data.get(274)
                if orientation == 3:
                    print('image rotate 180 度')
                    image.rotate(180, expand=True)
                    return image
                elif orientation == 6:
                    print('image rotate 270 度')
                    image.rotate(270, expand=True)
                    return image
                elif orientation == 8:
                    print('image rotate 90 度')
                    image.rotate(90, expand=True)
                    return image
            else:
                print('正常图片')
                return image
    
            trans_pose_image = ImageOps.exif_transpose(image)  # 也可以采用 这种方式 进行矫正
            return trans_pose_image  # 返回矫正后的图像
        except:
            print(traceback.print_exc())
            return None  # 异常情况反回空
    
    
    if __name__ == '__main__':
        img_path = 'test1.jpg'
        print(image_transpose(img_path))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    相关参考:
    [1]Python Image._getexif方法代码示例

    声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。

  • 相关阅读:
    Java终止线程的三种方式
    记一次 splice 导致 io.Copy 阻塞的排查过程
    ElasticSerach基础语法
    计算机视觉部分函数积累
    【C++11算法】minmax和minmax_element
    linux动静态库
    Flutter页面状态保留策略
    indiegogo/kickstarter海外众筹是什么
    Smart-tools 产品介绍
    Redis的Java客户端-Jedis
  • 原文地址:https://blog.csdn.net/XX_123_1_RJ/article/details/134012990