打开字节流作为图像文件以访问 exif 'UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 的字节 0xff:起始字节无效'

问题描述

当图像到达 DropBox上传到 Azure 存储时,我需要下载图像。我正在使用由 DropBox 的推送通知触发的 Kubeless 无服务器功能来执行此操作。此下载和上传工作正常。但是,我想访问图像的 exif 数据,以便我可以将有关图像的元数据发送到 RabbitMQ 队列。当我尝试打开图像以与 Python 的 Pillow 或 exif 模块一起使用时,出现此错误'UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte'

 dbx = dropBox.DropBox(os.environ['DROPBox_TOKEN'])
    for entry in dbx.files_list_folder('').entries:
        print('File found: ' + entry.name)
        md,response = dbx.files_download('/' + entry.name)

        file_stream = response.content

       # Code to upload to Azure Storage and delete file from DropBox here
       

我试过了:

       with open(file_stream,'rb') as data:
            # do things with file

并使用枕头:

image = Image.open(file_stream)
        image.show()

并且每个都得到相同的错误。我刚开始使用 Python 并以这种方式处理文件,因此不胜感激。

解决方法

我试图打开文件,而 file_stream 已经是打开的文件内容。

Python 请求文档提供了一个以适合我的方式使用 Pillow 的 Image.open() 的示例:

>>> from PIL import Image
>>> from io import BytesIO

>>> i = Image.open(BytesIO(r.content))

https://2.python-requests.org/en/master/user/quickstart/#binary-response-content

为了将来参考,这种打开图像的方式使我能够成功访问exif数据(img_exif = image.getexif()),而使用Image.fromBytes()时exif数据为空。我不知道为什么。