Skip to content

Commit b771a56

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 0652132 commit b771a56

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
@@ -498,24 +497,16 @@ def print_png(self, filename_or_obj, *args,
498497

499498
if metadata is None:
500499
metadata = {}
501-
if pil_kwargs is None:
502-
pil_kwargs = {}
503500
metadata = {
504501
"Software":
505502
f"matplotlib version{mpl.__version__}, http://matplotlib.org/",
506503
**metadata,
507504
}
508505
FigureCanvasAgg.draw(self)
509-
# Only use the metadata kwarg if pnginfo is not set, because the
510-
# semantics of duplicate keys in pnginfo is unclear.
511-
if "pnginfo" not in pil_kwargs:
512-
pnginfo = PngInfo()
513-
for k, v in metadata.items():
514-
pnginfo.add_text(k, v)
515-
pil_kwargs["pnginfo"] = pnginfo
516-
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
517-
(Image.fromarray(np.asarray(self.buffer_rgba()))
518-
.save(filename_or_obj, format="png", **pil_kwargs))
506+
mpl.image.imsave(
507+
filename_or_obj, np.asarray(self.buffer_rgba()), format="png",
508+
origin="upper", dpi=self.figure.dpi,
509+
metadata=metadata, pil_kwargs=pil_kwargs)
519510

520511
def print_to_buffer(self):
521512
FigureCanvasAgg.draw(self)

lib/matplotlib/image.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,8 +1527,10 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
15271527
pil_shape = (rgba.shape[1], rgba.shape[0])
15281528
image = PIL.Image.frombuffer(
15291529
"RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
1530-
if format == "png" and metadata is not None:
1531-
# cf. backend_agg's print_png.
1530+
if (format == "png"
1531+
and metadata is not None and "pnginfo" not in pil_kwargs):
1532+
# Only use the metadata kwarg if pnginfo is not set, because the
1533+
# semantics of duplicate keys in pnginfo is unclear.
15321534
pnginfo = PIL.PngImagePlugin.PngInfo()
15331535
for k, v in metadata.items():
15341536
pnginfo.add_text(k, v)

0 commit comments

Comments
 (0)