From 735d34260814f9180b773723fd741a7da73047ed Mon Sep 17 00:00:00 2001 From: Martin Fitzpatrick Date: Thu, 26 Mar 2015 13:25:26 +0100 Subject: [PATCH] Add support for HTTP response objects to Image.open() HTTP response objects returned from `urllib2.urlopen(url)` or `requests.get(url, stream=True).raw` are 'file-like' but do not support `.seek()` operations. As a result PIL is unable to open them as images, requiring a wrap in `cStringIO` or `BytesIO`. This commit adds this functionality to `Image.open()` by way of an `.seek(0)` check and catch on exception `AttributeError` or `io.UnsupportedOperation`. If this is caught we attempt to wrap the object using `io.BytesIO` (which will only work on buffer-file-like objects). This allows opening of files using both `urllib2` and `requests`, e.g. Image.open(urllib2.urlopen(url)) Image.open(requests.get(url, stream=True).raw) --- PIL/Image.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/PIL/Image.py b/PIL/Image.py index 2f304a9a8..58944f891 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -109,6 +109,7 @@ from PIL._util import deferred_error import os import sys +import io # type stuff import collections @@ -2248,6 +2249,11 @@ def open(fp, mode="r"): else: filename = "" + try: + fp.seek(0) + except (AttributeError, io.UnsupportedOperation): + fp = io.BytesIO(fp.read()) + prefix = fp.read(16) preinit()