FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Improve handling of alpha when saving to jpeg. · matplotlib/matplotlib@505a0cc · GitHub

Repository navigation

Commit 505a0cc

Browse files
committed
Improve handling of alpha when saving to jpeg.
We can compose the figure facecolor against a white background before rendering the image, rather than after. This saves an image composition step.
1 parent ce334d4 commit 505a0cc

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

‎lib/matplotlib/backends/backend_agg.py‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -563,23 +563,25 @@ def print_jpg(self, filename_or_obj, *args, dryrun=False, pil_kwargs=None,
563563
`PIL.Image.save` when saving the figure. These take precedence
564564
over *quality*, *optimize* and *progressive*.
565565
"""
566-
FigureCanvasAgg.draw(self)
566+
# The image is "pasted" onto a white background to handle transparency.
567+
r, g, b, a = mcolors.to_rgba(self.figure.get_facecolor())
568+
try:
569+
self.figure.set_facecolor(a * np.array([r, g, b]) + 1 - a)
570+
FigureCanvasAgg.draw(self)
571+
finally:
572+
self.figure.set_facecolor((r, g, b, a))
567573
if dryrun:
568574
return
569-
# The image is "pasted" onto a white background image to safely
570-
# handle any transparency
571-
image = Image.fromarray(np.asarray(self.buffer_rgba()))
572-
background = Image.new("RGB", image.size, "white")
573-
background.paste(image, image)
574575
if pil_kwargs is None:
575576
pil_kwargs = {}
576577
for k in ["quality", "optimize", "progressive"]:
577578
if k in kwargs:
578579
pil_kwargs.setdefault(k, kwargs[k])
579580
pil_kwargs.setdefault("quality", rcParams["savefig.jpeg_quality"])
580581
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
581-
return background.save(
582-
filename_or_obj, format='jpeg', **pil_kwargs)
582+
# Drop alpha channel now.
583+
return (Image.fromarray(np.asarray(self.buffer_rgba())[..., :3])
584+
.save(filename_or_obj, format='jpeg', **pil_kwargs))
583585

584586
print_jpeg = print_jpg
585587

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL