【问题标题】:Python exif orientation KeyError: '274'Python exif 方向 KeyError: '274'
【发布时间】:2022-03-28 18:58:36
【问题描述】:

上传图片时出现内部服务器错误。然后去heroku日志我看到这个KeyError

这是我的代码:

if request.method == "POST":
    user_id = session["user_id"]
    if request.files['photo']:
        filename = photos.save(request.files['photo'])
        extension = os.path.splitext(filename)[1]
        foo = Image.open("static/img/"+filename)
        exifimage = foo._getexif()
        if exifimage:
            for orientation in ExifTags.TAGS.keys() :
                if ExifTags.TAGS[orientation]=='Orientation':
                    break

            exif=dict(exifimage.items())

            if exif[orientation] == 3 :
                foo=foo.rotate(180, expand=True)
            elif exif[orientation] == 6 :
                foo=foo.rotate(270, expand=True)
            elif exif[orientation] == 8 :
                foo=foo.rotate(90, expand=True)

这是完整的错误:

if exif[orientation] == 3 :
KeyError: 274

为什么会发生这种情况?提前致谢

【问题讨论】:

  • 请提供minimal reproducible example。您从该错误消息中了解到什么?
  • 根据该错误信息,您认为发生错误时orientation 的值是多少?在exif 中用作键是否有意义?为什么或为什么不?
  • @AMC 此错误仅发生在从 Internet 下载的图像上,例如,如果您从相机胶卷上传图像,则不会返回任何错误
  • @KarlKnechtel 我对这些东西有点菜鸟,但我知道我需要这段代码,否则图像会被旋转。此错误仅发生在从 Internet 下载的图像中,如果您从相机胶卷上传照片,它将正常工作
  • 好的,但我问了 具体 问题,我是出于原因。你对 exif 数据格式了解多少?你究竟在哪里需要帮助?像“为什么”这样的问题在真空中是不可行的;我们需要知道您所处的位置,以便以对您有用的方式解释事情。

标签: python python-3.x image exif


【解决方案1】:

我相信我遇到了同样的问题。

如果图像文件有EXIF数据,它将正常工作,否则没有什么可以读入并抛出异常。 (此外,如果您将矩形图像旋转 90 度或 270 度,您很可能希望翻转高度和宽度,以便画布与新方向匹配。)

你应该放入一个 try 块:

try:
    exif_data = open_image.getexif()
    for orientation in ExifTags.TAGS.keys():
        if ExifTags.TAGS[orientation]=='Orientation':
            break
    print ("Rotation: " + str(exif_data[orientation]))
    if exif_data[orientation] == 3:
        open_image = open_image.rotate(180, expand=True)
    elif exif_data[orientation] == 6:
        open_image = open_image.rotate(270, expand=True)
        img_picture_width, img_picture_height = img_picture_height, img_picture_width
    elif exif_data[orientation] == 8:
        open_image = open_image.rotate(90, expand=True)
        img_picture_width, img_picture_height = img_picture_height, img_picture_width
except Exception as e:
    print ("Exif data spinning errored (might have no exif data)")
    print (e)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2014-06-06
    相关资源
    最近更新 更多