2.8.0#

使用image.open打开HTTP响应对象#

从返回的HTTP响应对象 urllib2.urlopen(url)requests.get(url, stream=True).raw 是“类似文件”但不支持 .seek() 操作。结果,PIL无法将它们作为图像打开,需要一个包装 cStringIOBytesIO .

现在新功能已添加到 Image.open() 通过 .seek(0) 检查并捕获异常 AttributeErrorio.UnsupportedOperation 。如果这被发现,我们试图用 io.BytesIO (只对缓冲区文件(如对象)有效)。

这允许使用两种方法打开文件 urllib2requests ,例如:

Image.open(urllib2.urlopen(url))
Image.open(requests.get(url, stream=True).raw)

如果响应使用内容编码(压缩,gzip或deflate),那么这将失败,因为在这种情况下,urllib2和requests raw file对象都将生成压缩数据。在图像上使用内容编码是相当不感性的,因为大多数图像已经被压缩,但它仍然可能发生。

对于请求,解决方法是将原始对象的decode_content属性设置为true::

response = requests.get(url, stream=True)
response.raw.decode_content = True
image = Image.open(response.raw)