8000 Allow saving PNGs through Pillow instead of the builtin _png module. by anntzer · Pull Request #13207 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Allow saving PNGs through Pillow instead of the builtin _png module. #13207

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions doc/users/next_whats_new/2018-01-03-AL.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@
Matplotlib uses Pillow to handle saving to the JPEG and TIFF formats. The
`~Figure.savefig()` function gained a *pil_kwargs* keyword argument, which can
be used to forward arguments to Pillow's `PIL.Image.save()`.

The *pil_kwargs* argument can also be used when saving to PNG. In that case,
Matplotlib also uses Pillow's `PIL.Image.save()` instead of going through its
own builtin PNG support.
52 changes: 39 additions & 13 deletions lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,9 @@ def print_raw(self, filename_or_obj, *args, **kwargs):

print_rgba = print_raw

def print_png(self, filename_or_obj, *args, **kwargs):
def print_png(self, filename_or_obj, *args,
metadata=None, pil_kwargs=None,
**kwargs):
"""
Write the figure to a PNG file.

Expand Down Expand Up @@ -494,21 +496,45 @@ def print_png(self, filename_or_obj, *args, **kwargs):
.. _PNG specification: \
https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords

pil_kwargs : dict, optional
If set to a non-None value, use Pillow to save the figure instead
of Matplotlib's builtin PNG support, and pass these keyword
arguments to `PIL.Image.save`.

If the 'pnginfo' key is present, it completely overrides
*metadata*, including the default 'Software' key.
"""
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()

version_str = (
'matplotlib version ' + __version__ + ', http://matplotlib.org/')
metadata = OrderedDict({'Software': version_str})
user_metadata = kwargs.pop("metadata", None)
if user_metadata is not None:
metadata.update(user_metadata)
if metadata is None:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Randomly surfing this change from a watched issue

Why initing metadata = {} is just a line below it's inited to something else again?

https://github.com/anntzer/matplotlib/blob/9c7f926d6d70a994c3710ce570bb9807519ef090/lib/matplotlib/backends/backend_agg.py#L509

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's used on line 513.

metadata = {}
metadata = {
"Software":
f"matplotlib version{__version__}, http://matplotlib.org/",
**metadata,
}

with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
cbook.open_file_cm(filename_or_obj, "wb") as fh:
_png.write_png(renderer._renderer, fh,
self.figure.dpi, metadata=metadata)
if pil_kwargs is not None:
from PIL import Image
from PIL.PngImagePlugin import PngInfo
buf, size = self.print_to_buffer()
# Only use the metadata kwarg if pnginfo is not set, because the
# semantics of duplicate keys in pnginfo is unclear.
if "pnginfo" not in pil_kwargs:
pnginfo = PngInfo()
for k, v in metadata.items():
pnginfo.add_text(k, v)
pil_kwargs["pnginfo"] = pnginfo
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a little confusing - if the user passes dpi=200 to savefig it will be ignored in lieu of self.figure.dpi? Is there no way to pass the dpi from savefig as the default instead (of course falling back to self.figure.dpi?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See discussion in #13094 (review).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah right. I even saw that at the time. (though, maybe a comment here though just to remind the unwary).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks fine to me once it passes the test...

(Image.frombuffer("RGBA", size, buf, "raw", "RGBA", 0, 1)
.save(filename_or_obj, format="png", **pil_kwargs))

else:
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
cbook.open_file_cm(filename_or_obj, "wb") as fh:
_png.write_png(renderer._renderer, fh,
self.figure.dpi, metadata=metadata)

def print_to_buffer(self):
FigureCanvasAgg.draw(self)
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2106,7 +2106,8 @@ def savefig(self, fname, *, frameon=None, transparent=None, **kwargs):
pil_kwargs : dict, optional
Additional keyword arguments that are passed to `PIL.Image.save`
when saving the figure. Only applicable for formats that are saved
using Pillow, i.e. JPEG and TIFF.
using Pillow, i.e. JPEG, TIFF, and (if the keyword is set to a
non-None value) PNG.
"""

kwargs.setdefault('dpi', rcParams['savefig.dpi'])
Expand Down
13 changes: 12 additions & 1 deletion lib/matplotlib/tests/test_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,18 @@ def test_jpeg_dpi():
assert im.info['dpi'] == (200, 200)


def test_pil_kwargs():
def test_pil_kwargs_png():
Image = pytest.importorskip("PIL.Image")
from PIL.PngImagePlugin import PngInfo
buf = io.BytesIO()
pnginfo = PngInfo()
pnginfo.add_text("Software", "test")
plt.figure().savefig(buf, format="png", pil_kwargs={"pnginfo": pnginfo})
im = Image.open(buf)
assert im.info["Software"] == "test"


def test_pil_kwargs_tiff():
Image = pytest.importorskip("PIL.Image")
from PIL.TiffTags import TAGS_V2 as TAGS
buf = io.BytesIO()
Expand Down
0