Skip to content

Commit f1677a7

Browse files
committed
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).
1 parent d576e3a commit f1677a7

File tree

2 files changed

+4
-7
lines changed

2 files changed

+4
-7
lines changed

lib/matplotlib/backends/backend_agg.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -584,12 +584,10 @@ def print_jpg(self, filename_or_obj, *args, dryrun=False,
584584
FigureCanvasAgg.draw(self)
585585
if dryrun:
586586
return
587-
# The image is "pasted" onto a white background image to safely
588-
# handle any transparency
587+
# The image is pasted onto a white background image to handle
588+
# transparency.
589589
image = Image.fromarray(np.asarray(self.buffer_rgba()))
590-
rgba = mcolors.to_rgba(rcParams['savefig.facecolor'])
591-
color = tuple([int(x * 255) for x in rgba[:3]])
592-
background = Image.new('RGB', image.size, color)
590+
background = Image.new('RGB', image.size, "white")
593591
background.paste(image, image)
594592
if pil_kwargs is None:
595593
pil_kwargs = {}

lib/matplotlib/tests/test_image.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -674,8 +674,7 @@ def test_jpeg_alpha():
674674
plt.figimage(im)
675675

676676
buff = io.BytesIO()
677-
with rc_context({'savefig.facecolor': 'red'}):
678-
plt.savefig(buff, transparent=True, format='jpg', dpi=300)
677+
plt.savefig(buff, facecolor="red", format='jpg', dpi=300)
679678

680679
buff.seek(0)
681680
image = Image.open(buff)

0 commit comments

Comments
 (0)