8000 Merge pull request #972 from cgohlke/patch-8 · matplotlib/matplotlib@7a6897e · GitHub
[go: up one dir, main page]

Skip to content

Commit 7a6897e

Browse files
committed
Merge pull request #972 from cgohlke/patch-8
Force closing PIL image files
2 parents 352467c + ac68802 commit 7a6897e

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

lib/matplotlib/image.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,12 +1185,20 @@ def imread(fname, format=None):
11851185
can be used with :func:`~matplotlib.pyplot.imshow`.
11861186
"""
11871187

1188-
def pilread():
1188+
def pilread(fname):
11891189
"""try to load the image with PIL or return None"""
1190-
try: from PIL import Image
1191-
except ImportError: return None
1192-
image = Image.open( fname )
1193-
return pil_to_array(image)
1190+
try:
1191+
from PIL import Image
1192+
except ImportError:
1193+
return None
1194+
if cbook.is_string_like(fname):
1195+
# force close the file after reading the image
1196+
with open(fname, "rb") as fh:
1197+
image = Image.open(fh)
1198+
return pil_to_array(image)
1199+
else:
1200+
image = Image.open(fname)
1201+
return pil_to_array(image)
11941202

11951203
handlers = {'png' :_png.read_png, }
11961204
if format is None:
@@ -1206,7 +1214,7 @@ def pilread():
12061214
ext = format
12071215

12081216
if ext not in handlers.iterkeys():
1209-
im = pilread()
1217+
im = pilread(fname)
12101218
if im is None:
12111219
raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys())
12121220
return im

0 commit comments

Comments
 (0)
0