Skip to content
This repository
Browse code

Merge pull request #972 from cgohlke/patch-8

Force closing PIL image files
  • Loading branch information...
commit 7a6897eea7c47999b76a56d9e51bbbf50ca6ca5c 2 parents 352467c + ac68802
Phil Elson authored July 17, 2012

Showing 1 changed file with 14 additions and 6 deletions. Show diff stats Hide diff stats

  1. 20  lib/matplotlib/image.py
20  lib/matplotlib/image.py
@@ -1185,12 +1185,20 @@ def imread(fname, format=None):
1185 1185
     can be used with :func:`~matplotlib.pyplot.imshow`.
1186 1186
     """
1187 1187
 
1188  
-    def pilread():
  1188
+    def pilread(fname):
1189 1189
         """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)
1194 1202
 
1195 1203
     handlers = {'png' :_png.read_png, }
1196 1204
     if format is None:
@@ -1206,7 +1214,7 @@ def pilread():
1206 1214
         ext = format
1207 1215
 
1208 1216
     if ext not in handlers.iterkeys():
1209  
-        im = pilread()
  1217
+        im = pilread(fname)
1210 1218
         if im is None:
1211 1219
             raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys())
1212 1220
         return im

0 notes on commit 7a6897e

Please sign in to comment.
Something went wrong with that request. Please try again.