操作系统错误:尝试重用下载的标头时无法识别图像文件<_io.BytesIO object at 0x02F41960>

问题描述 投票:0回答:1

Image.open 最后失败:

文件“C:\Program Files (x86)\Python36-32\lib\site-packages\PIL\Image.py”,第 2349 行,打开 %(文件名,如果文件名,否则fp))

OSError:无法识别图像文件

<_io.BytesIO object at 0x02F41960>

我发现
Pillow 的发行说明 2.8.0

这似乎表明我可以使用 Image.open(requests.raw)。我猜想在确保使用seek(0)重置它之后我应该能够重用已经下载的标头。 此错误的其他答案似乎涉及将图像缓冲区保存到实际文件中,

我试图避免

(只是重用从response.raw下载的字节进行我的所有测试/检查,而不是发出多个下载请求到任何服务器。) 请问我哪里错了?

这是我的示例代码:

import requests from PIL import Image import imghdr import io if __name__ == '__main__': url = "https://ichef-1.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg" try: response = requests.get(url, stream=True) if response.status_code == 200: response.raw.decode_content = True # Grab first 100 bytes as potential image header header = response.raw.read(100) ext = imghdr.what(None, h=header) print("Found: " + ext) if ext != None: # Proceed to other tests if we received an image at all header = io.BytesIO(header) header.seek(0) im = Image.open(header) im.verify() # other image-related tasks here else: print("Received error " + str(response.status.code)) except requests.ConnectionError as e: print(e)


python image python-3.x python-requests python-imaging-library
1个回答
0
投票
Image.open()

之前获取其余的图像数据。


这就是我的意思:

import requests from PIL import Image import imghdr import io if __name__ == '__main__': url = "https://ichef-1.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg" try: response = requests.get(url, stream=True) if response.status_code == 200: response.raw.decode_content = True # Grab first 100 bytes as potential image header header = response.raw.read(100) ext = imghdr.what(None, h=header) print("Found: " + ext) if ext != None: # Proceed to other tests if we received an image at all data = header + response.raw.read() # GET THE REST OF THE FILE data = io.BytesIO(data) im = Image.open(data) im.verify() # other image-related tasks here else: print("Received error " + str(response.status.code)) except requests.ConnectionError as e: print(e)

© www.soinside.com 2019 - 2024. All rights reserved.