Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7aad47a

Browse files
committed
Reuse png metadata handling of imsave() in FigureCanvasAgg.print_png().
This avoids duplicating the conversion of metadata to PngInfo and revealed a bug in the priority between `metadata` and `pil_kwargs` in imsave(). Note that because `np.asarray(self.buffer_rgba())` is already a RGBA uint8 array, there is no colormapping step happening in imsave(). Ideally mplcairo should also be able to use imsave() for saving to png.
1 parent 898bd5f commit 7aad47a

File tree

2 files changed

+8
-15
lines changed

2 files changed

+8
-15
lines changed

lib/matplotlib/backends/backend_agg.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333

3434
import numpy as np
3535
from PIL import Image
36-
from PIL.PngImagePlugin import PngInfo
3736

3837
import matplotlib as mpl
3938
from matplotlib import cbook
@@ -502,24 +501,16 @@ def print_png(self, filename_or_obj, *args,
502501

503502
if metadata is None:
504503
metadata = {}
505-
if pil_kwargs is None:
506-
pil_kwargs = {}
507504
metadata = {
508505
"Software":
509506
f"matplotlib version{mpl.__version__}, http://matplotlib.org/",
510507
**metadata,
511508
}
512509
FigureCanvasAgg.draw(self)
513-
# Only use the metadata kwarg if pnginfo is not set, because the
514-
# semantics of duplicate keys in pnginfo is unclear.
515-
if "pnginfo" not in pil_kwargs:
516-
pnginfo = PngInfo()
517-
for k, v in metadata.items():
518-
pnginfo.add_text(k, v)
519-
pil_kwargs["pnginfo"] = pnginfo
520-
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
521-
(Image.fromarray(np.asarray(self.buffer_rgba()))
522-
.save(filename_or_obj, format="png", **pil_kwargs))
510+
mpl.image.imsave(
511+
filename_or_obj, np.asarray(self.buffer_rgba()), format="png",
512+
origin="upper", dpi=self.figure.dpi,
513+
metadata=metadata, pil_kwargs=pil_kwargs)
523514

524515
def print_to_buffer(self):
525516
FigureCanvasAgg.draw(self)

lib/matplotlib/image.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1520,8 +1520,10 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
15201520
pil_shape = (rgba.shape[1], rgba.shape[0])
15211521
image = PIL.Image.frombuffer(
15221522
"RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
1523-
if format == "png" and metadata is not None:
1524-
# cf. backend_agg's print_png.
1523+
if (format == "png"
1524+
and metadata is not None and "pnginfo" not in pil_kwargs):
1525+
# Only use the metadata kwarg if pnginfo is not set, because the
1526+
# semantics of duplicate keys in pnginfo is unclear.
15251527
pnginfo = PIL.PngImagePlugin.PngInfo()
15261528
for k, v in metadata.items():
15271529
pnginfo.add_text(k, v)

0 commit comments

Comments
 (0)