From f1677a71ff1c696506f59b62578544f8048de99d Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Mon, 9 Sep 2019 22:35:06 +0200 Subject: [PATCH] Composite against white, not the savefig.facecolor rc, in print_jpeg. jpeg doesn't support alpha transparency, so we need to paste the image against some solid background before saving it. Pasting against the savefig.facecolor rc, as the code did before, is just wrong: it makes e.g. ``` plot([1, 2]) rcParams["savefig.facecolor"] = "blue" savefig("/tmp/foo.jpg", facecolor=(1, 0, 0, .5)) ``` result in a purple background (blue + 0.5 red), instead of a red one (as for png -- the facecolor kwarg should just override the rcParam). Likewise the test_jpeg_alpha test was just wrong (indeed, trying to run the same code but saving as png shows that transparent=True should override the savefig.facecolor rcParam). Instead, paste the image against a white background, which fixes the issues (and is tested by the fixed test_jpeg_alpha). --- lib/matplotlib/backends/backend_agg.py | 8 +++----- lib/matplotlib/tests/test_image.py | 3 +-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/lib/matplotlib/backends/backend_agg.py b/lib/matplotlib/backends/backend_agg.py index c2caea38a043..cf9c54123050 100644 --- a/lib/matplotlib/backends/backend_agg.py +++ b/lib/matplotlib/backends/backend_agg.py @@ -584,12 +584,10 @@ def print_jpg(self, filename_or_obj, *args, dryrun=False, FigureCanvasAgg.draw(self) if dryrun: return - # The image is "pasted" onto a white background image to safely - # handle any transparency + # The image is pasted onto a white background image to handle + # transparency. image = Image.fromarray(np.asarray(self.buffer_rgba())) - rgba = mcolors.to_rgba(rcParams['savefig.facecolor']) - color = tuple([int(x * 255) for x in rgba[:3]]) - background = Image.new('RGB', image.size, color) + background = Image.new('RGB', image.size, "white") background.paste(image, image) if pil_kwargs is None: pil_kwargs = {} diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index d56e5d3d9eb4..00f742f66596 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -674,8 +674,7 @@ def test_jpeg_alpha(): plt.figimage(im) buff = io.BytesIO() - with rc_context({'savefig.facecolor': 'red'}): - plt.savefig(buff, transparent=True, format='jpg', dpi=300) + plt.savefig(buff, facecolor="red", format='jpg', dpi=300) buff.seek(0) image = Image.open(buff)