【问题标题】:PIL cannot identify image file for a Google Drive image streamd into io.BytesIOPIL 无法识别流入 io.BytesIO 的 Google Drive 图像的图像文件
【发布时间】:2018-07-13 12:29:24
【问题描述】:

我正在使用 Drive API 下载image。在他们用 Python 下载 documentation 的文件之后,我最终得到了一个变量 fh,它是一个填充的 io.BytesIO 实例。我尝试将其另存为图像:

file_id = "0BwyLGoHzn5uIOHVycFZpSEwycnViUjFYQXR5Nnp6QjBrLXJR"
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print('Download {} {}%.'.format(file['name'],
                                    int(status.progress() * 100)))
    fh.seek(0)
image = Image.open(fh) # error

错误是:cannot identify image file <_io.BytesIO object at 0x106cba890>。实际上,another image 不会发生错误,但大多数图像都会引发错误,包括我在本文开头链接的那个。

阅读this answer 后,我将最后一行更改为:

byteImg = fh.read()
dataBytesIO = io.BytesIO(byteImg)
image = Image.open(dataBytesIO) # still the same error

我也尝试过this answer,将我的第一个代码块的最后一行更改为

byteImg = fh.read()
image = Image.open(StringIO(byteImg))

但我仍然收到 cannot identify image file <StringIO.StringIO instance at 0x106471e60> 错误。

我尝试使用替代项(请求、urllib)但没有结果。如果我手动下载图片,我可以Image.open 图片。

此错误在一个月前不存在,最近在此代码所在的应用程序中弹出。我花了几天时间调试此错误但没有成功,最终将问题提交给 Stack Overflow。我正在使用from PIL import Image

【问题讨论】:

    标签: python google-drive-api python-imaging-library stringio bytesio


    【解决方案1】:

    放弃云端硬盘服务的MediaIOBaseDownload。而是使用媒体文件的webContentLink 属性(用于在浏览器中下载文件内容的链接,仅适用于具有二进制内容的文件)。阅读更多here

    通过该内容链接,我们可以使用另一种形式的流式传输——requestsshutil 库和——来获取图像。

    import requests
    import shutil
    
    r = requests.get(file['webContentLink'], stream=True)
    with open('output_file', 'wb') as f:
        shutil.copyfileobj(r.raw, f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多