Skip to content

Commit b779492

Browse files
authored
Merge pull request #15095 from anntzer/pngfile
Simplify _png extension by handling file open/close in Python.
2 parents a0b8cae + c26a151 commit b779492

File tree

8 files changed

+63
-153
lines changed

8 files changed

+63
-153
lines changed

lib/matplotlib/backends/backend_pgf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -639,7 +639,8 @@ def draw_image(self, gc, x, y, im, transform=None):
639639
fname = os.path.splitext(os.path.basename(self.fh.name))[0]
640640
fname_img = "%s-img%d.png" % (fname, self.image_counter)
641641
self.image_counter += 1
642-
_png.write_png(im[::-1], os.path.join(path, fname_img))
642+
with pathlib.Path(path, fname_img).open("wb") as file:
643+
_png.write_png(im[::-1], file)
643644

644645
# reference the image in the pgf picture
645646
writeln(self.fh, r"\begin{pgfscope}")

lib/matplotlib/backends/backend_svg.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -821,20 +821,20 @@ def draw_image(self, gc, x, y, im, transform=None):
821821
if url is not None:
822822
self.writer.start('a', attrib={'xlink:href': url})
823823
if rcParams['svg.image_inline']:
824-
bytesio = io.BytesIO()
825-
_png.write_png(im, bytesio)
826-
oid = oid or self._make_id('image', bytesio.getvalue())
824+
buf = _png.write_png(im, None)
825+
oid = oid or self._make_id('image', buf)
827826
attrib['xlink:href'] = (
828827
"data:image/png;base64,\n" +
829-
base64.b64encode(bytesio.getvalue()).decode('ascii'))
828+
base64.b64encode(buf).decode('ascii'))
830829
else:
831830
if self.basename is None:
832831
raise ValueError("Cannot save image data to filesystem when "
833832
"writing SVG to an in-memory buffer")
834833
filename = '{}.image{}.png'.format(
835834
self.basename, next(self._image_counter))
836835
_log.info('Writing image file for inclusion: %s', filename)
837-
_png.write_png(im, filename)
836+
with open(filename, 'wb') as file:
837+
_png.write_png(im, file)
838838
oid = oid or 'Im_' + self._make_id('image', filename)
839839
attrib['xlink:href'] = filename
840840

lib/matplotlib/image.py

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -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

14451430
def 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

lib/matplotlib/mathtext.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3433,7 +3433,8 @@ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
34333433
from matplotlib import _png
34343434
rgba, depth = self.to_rgba(
34353435
texstr, color=color, dpi=dpi, fontsize=fontsize)
3436-
_png.write_png(rgba, filename)
3436+
with open(filename, "wb") as file:
3437+
_png.write_png(rgba, file)
34373438
return depth
34383439

34393440
def get_depth(self, texstr, dpi=120, fontsize=14):

lib/matplotlib/testing/compare.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -384,10 +384,10 @@ def compare_images(expected, actual, tol, in_decorator=False):
384384
expected = convert(expected, True)
385385

386386
# open the image files and remove the alpha channel (if it exists)
387-
expected_image = _png.read_png_int(expected)
388-
actual_image = _png.read_png_int(actual)
389-
expected_image = expected_image[:, :, :3]
390-
actual_image = actual_image[:, :, :3]
387+
with open(expected, "rb") as expected_file:
388+
expected_image = _png.read_png_int(expected_file)[:, :, :3]
389+
with open(actual, "rb") as actual_file:
390+
actual_image = _png.read_png_int(actual_file)[:, :, :3]
391391

392392
actual_image, expected_image = crop_to_same(
393393
actual, actual_image, expected, expected_image)
@@ -438,8 +438,10 @@ def save_diff_image(expected, actual, output):
438438
'''
439439
# Drop alpha channels, similarly to compare_images.
440440
from matplotlib import _png
441-
expected_image = _png.read_png(expected)[..., :3]
442-
actual_image = _png.read_png(actual)[..., :3]
441+
with open(expected, "rb") as expected_file:
442+
expected_image = _png.read_png(expected_file)[..., :3]
443+
with open(actual, "rb") as actual_file:
444+
actual_image = _png.read_png(actual_file)[..., :3]
443445
actual_image, expected_image = crop_to_same(
444446
actual, actual_image, expected, expected_image)
445447
expected_image = np.array(expected_image).astype(float)
@@ -465,4 +467,5 @@ def save_diff_image(expected, actual, output):
465467
# Hard-code the alpha channel to fully solid
466468
save_image_np[:, :, 3] = 255
467469

468-
_png.write_png(save_image_np, output)
470+
with open(output, "wb") as output_file:
471+
_png.write_png(save_image_np, output_file)

lib/matplotlib/tests/test_png.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from io import BytesIO
22
import glob
33
import os
4+
from pathlib import Path
5+
46
import numpy as np
57
import pytest
68

@@ -33,9 +35,9 @@ def test_pngsuite():
3335

3436
def test_imread_png_uint16():
3537
from matplotlib import _png
36-
img = _png.read_png_int(os.path.join(os.path.dirname(__file__),
37-
'baseline_images/test_png/uint16.png'))
38-
38+
with (Path(__file__).parent
39+
/ 'baseline_images/test_png/uint16.png').open('rb') as file:
40+
img = _png.read_png_int(file)
3941
assert (img.dtype == np.uint16)
4042
assert np.sum(img.flatten()) == 134184960
4143

lib/matplotlib/texmanager.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,8 @@ def get_grey(self, tex, fontsize=None, dpi=None):
403403
alpha = self.grey_arrayd.get(key)
404404
if alpha is None:
405405
pngfile = self.make_png(tex, fontsize, dpi)
406-
X = _png.read_png(os.path.join(self.texcache, pngfile))
406+
with open(os.path.join(self.texcache, pngfile), "rb") as file:
407+
X = _png.read_png(file)
407408
self.grey_arrayd[key] = alpha = X[:, :, -1]
408409
return alpha
409410

0 commit comments

Comments
 (0)