77 unicode_literals )
88
99import six
10+ from six .moves .urllib .parse import urlparse
11+ from six .moves .urllib .request import urlopen
12+ from six import BytesIO
1013
1114import os
1215import warnings
@@ -1230,8 +1233,9 @@ def imread(fname, format=None):
12301233 """
12311234 Read an image from a file into an array.
12321235
1233- *fname* may be a string path or a Python file-like object. If
1234- using a file object, it must be opened in binary mode.
1236+ *fname* may be a string path, a valid URL, or a Python
1237+ file-like object. If using a file object, it must be opened in binary
1238+ mode.
12351239
12361240 If *format* is provided, will try to read file of that type,
12371241 otherwise the format is deduced from the filename. If nothing can
@@ -1244,7 +1248,9 @@ def imread(fname, format=None):
12441248 matplotlib can only read PNGs natively, but if `PIL
12451249 <http://www.pythonware.com/products/pil/>`_ is installed, it will
12461250 use it to load the image and return an array (if possible) which
1247- can be used with :func:`~matplotlib.pyplot.imshow`.
1251+ can be used with :func:`~matplotlib.pyplot.imshow`. Note, URL strings
1252+ may not be compatible with PIL. Check the PIL documentation for more
1253+ information.
12481254 """
12491255
12501256 def pilread (fname ):
@@ -1253,20 +1259,19 @@ def pilread(fname):
12531259 from PIL import Image
12541260 except ImportError :
12551261 return None
1256- if cbook .is_string_like (fname ):
1257- # force close the file after reading the image
1258- with open (fname , "rb" ) as fh :
1259- image = Image .open (fh )
1260- return pil_to_array (image )
1261- else :
1262- image = Image .open (fname )
1263- return pil_to_array (image )
1262+ image = Image .open (fname )
1263+ return pil_to_array (image )
12641264
12651265 handlers = {'png' : _png .read_png , }
12661266 if format is None :
12671267 if cbook .is_string_like (fname ):
1268- basename , ext = os .path .splitext (fname )
1269- ext = ext .lower ()[1 :]
1268+ parsed = urlparse (fname )
1269+ # If the string is a URL, assume png
1270+ if parsed .scheme != '' :
1271+ ext = 'png'
1272+ else :
1273+ basename , ext = os .path .splitext (fname )
1274+ ext = ext .lower ()[1 :]
12701275 elif hasattr (fname , 'name' ):
12711276 basename , ext = os .path .splitext (fname .name )
12721277 ext = ext .lower ()[1 :]
@@ -1289,8 +1294,14 @@ def pilread(fname):
12891294 # reader extension, since Python handles them quite well, but it's
12901295 # tricky in C.
12911296 if cbook .is_string_like (fname ):
1292- with open (fname , 'rb' ) as fd :
1297+ parsed = urlparse (fname )
1298+ # If fname is a URL, download the data
1299+ if parsed .scheme != '' :
1300+ fd = BytesIO (urlopen (fname ).read ())
12931301 return handler (fd )
1302+ else :
1303+ with open (fname , 'rb' ) as fd :
1304+ return handler (fd )
12941305 else :
12951306 return handler (fname )
12961307
0 commit comments