首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python exif orientation KeyError:'274‘

Python exif orientation KeyError:'274‘
EN

Stack Overflow用户
提问于 2020-06-29 06:27:56
回答 1查看 146关注 0票数 0

当上传和图像时,我得到一个内部服务器错误。然后转到heroku日志,我看到这个KeyError

这是我的代码:

代码语言:javascript
复制
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)

这是完整的错误:

代码语言:javascript
复制
if exif[orientation] == 3 :
KeyError: 274

为什么会发生这样的事情?提前感谢

EN

回答 1

Stack Overflow用户

发布于 2021-09-10 05:59:39

我想我也遇到过同样的问题。

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

您应该放入try块:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62628874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档