From 566a7af54b1c6f29f4e2540f8a7cb23340b95902 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Sun, 8 Mar 2020 00:51:45 -0500 Subject: [PATCH 1/2] Fix saving PNGs to file objects in some places. --- lib/matplotlib/image.py | 2 +- lib/matplotlib/mathtext.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 4fa365a696dd..734573595bc9 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -666,7 +666,7 @@ def write_png(self, fname): from matplotlib import _png im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A, bytes=True, norm=True) - with open(fname, "wb") as file: + with cbook.open_file_cm(fname, "wb") as file: _png.write_png(im, file) def set_data(self, A): diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index 3c1ba5750cf4..b875516cf440 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -3433,7 +3433,7 @@ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14): from matplotlib import _png rgba, depth = self.to_rgba( texstr, color=color, dpi=dpi, fontsize=fontsize) - with open(filename, "wb") as file: + with cbook.open_file_cm(filename, "wb") as file: _png.write_png(rgba, file) return depth From 5484892c495c63ff41e23ae33c5e772c9e9691b9 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Sun, 8 Mar 2020 01:06:07 -0500 Subject: [PATCH 2/2] Add smoke test that saving MathText to PNG works. --- lib/matplotlib/tests/test_mathtext.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index fdf930184070..508e29fa0880 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -280,3 +280,14 @@ def test_single_minus_sign(): def test_spaces(fig_test, fig_ref): fig_test.subplots().set_title(r"$1\,2\>3\ 4$") fig_ref.subplots().set_title(r"$1\/2\:3~4$") + + +def test_math_to_image(tmpdir): + mathtext.math_to_image('$x^2$', str(tmpdir.join('example.png'))) + mathtext.math_to_image('$x^2$', io.BytesIO()) + + +def test_mathtext_to_png(tmpdir): + mt = mathtext.MathTextParser('bitmap') + mt.to_png(str(tmpdir.join('example.png')), '$x^2$') + mt.to_png(io.BytesIO(), '$x^2$')