Skip to content

Commit

Permalink
Merge pull request #972 from cgohlke/patch-8
Browse files Browse the repository at this point in the history
Force closing PIL image files
  • Loading branch information
pelson committed Jul 18, 2012
2 parents 352467c + ac68802 commit 7a6897e
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1185,12 +1185,20 @@ def imread(fname, format=None):
can be used with :func:`~matplotlib.pyplot.imshow`.
"""

def pilread():
def pilread(fname):
"""try to load the image with PIL or return None"""
try: from PIL import Image
except ImportError: return None
image = Image.open( fname )
return pil_to_array(image)
try:
from PIL import Image
except ImportError:
return None
if cbook.is_string_like(fname):
# force close the file after reading the image
with open(fname, "rb") as fh:
image = Image.open(fh)
return pil_to_array(image)
else:
image = Image.open(fname)
return pil_to_array(image)

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

if ext not in handlers.iterkeys():
im = pilread()
im = pilread(fname)
if im is None:
raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys())
return im
Expand Down

0 comments on commit 7a6897e

Please sign in to comment.