@@ -645,7 +645,8 @@ def write_png(self, fname):
645645 from matplotlib import _png
646646 im = self .to_rgba (self ._A [::- 1 ] if self .origin == 'lower' else self ._A ,
647647 bytes = True , norm = True )
648- _png .write_png (im , fname )
648+ with open (fname , "wb" ) as file :
649+ _png .write_png (im , file )
649650
650651 def set_data (self , A ):
651652 """
@@ -1382,12 +1383,6 @@ def imread(fname, format=None):
13821383
13831384 .. _Pillow documentation: http://pillow.readthedocs.io/en/latest/
13841385 """
1385-
1386- def read_png (* args , ** kwargs ):
1387- from matplotlib import _png
1388- return _png .read_png (* args , ** kwargs )
1389-
1390- handlers = {'png' : read_png , }
13911386 if format is None :
13921387 if isinstance (fname , str ):
13931388 parsed = urllib .parse .urlparse (fname )
@@ -1412,34 +1407,24 @@ def read_png(*args, **kwargs):
14121407 ext = 'png'
14131408 else :
14141409 ext = format
1415-
1416- if ext not in handlers : # Try to load the image with PIL.
1417- try :
1410+ if ext != 'png' :
1411+ try : # Try to load the image with PIL.
14181412 from PIL import Image
14191413 except ImportError :
1420- raise ValueError ('Only know how to handle extensions: %s; '
1421- 'with Pillow installed matplotlib can handle '
1422- 'more images' % list (handlers ))
1414+ raise ValueError ('Only know how to handle PNG; with Pillow '
1415+ 'installed, Matplotlib can handle more images' )
14231416 with Image .open (fname ) as image :
14241417 return pil_to_array (image )
1425-
1426- handler = handlers [ext ]
1427-
1428- # To handle Unicode filenames, we pass a file object to the PNG
1429- # reader extension, since Python handles them quite well, but it's
1430- # tricky in C.
1418+ from matplotlib import _png
14311419 if isinstance (fname , str ):
14321420 parsed = urllib .parse .urlparse (fname )
14331421 # If fname is a URL, download the data
14341422 if len (parsed .scheme ) > 1 :
14351423 from urllib import request
14361424 fd = BytesIO (request .urlopen (fname ).read ())
1437- return handler (fd )
1438- else :
1439- with open (fname , 'rb' ) as fd :
1440- return handler (fd )
1441- else :
1442- return handler (fname )
1425+ return _png .read_png (fd )
1426+ with cbook .open_file_cm (fname , "rb" ) as file :
1427+ return _png .read_png (file )
14431428
14441429
14451430def imsave (fname , arr , vmin = None , vmax = None , cmap = None , format = None ,
@@ -1516,7 +1501,8 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
15161501 arr = arr [::- 1 ]
15171502 rgba = sm .to_rgba (arr , bytes = True )
15181503 if format == "png" and pil_kwargs is None :
1519- _png .write_png (rgba , fname , dpi = dpi , metadata = metadata )
1504+ with cbook .open_file_cm (fname , "wb" ) as file :
1505+ _png .write_png (rgba , file , dpi = dpi , metadata = metadata )
15201506 else :
15211507 try :
15221508 from PIL import Image
0 commit comments