8000 Edit error messages for when metadata is passed to `savefig` (#25430) · matplotlib/matplotlib@43c35e7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 43c35e7

Browse files
authored
Edit error messages for when metadata is passed to savefig (#25430)
* Edit error messages for when metadata is passed to `savefig` Closes #25401 As requested, the error message is more related to what users are actually doing. Slight behavior change, though not sure it's worth a release note in that `imsave` will error if metadata is given for formats that don't support it (this was done because it was unused if it was passed, and if and when we add metadata support for those formats, it will be implemented in imsave) * Make metadata kwonly for print_raw
1 parent 4bfa5f5 commit 43c35e7

File tree

4 files changed

+28
-7
lines changed

4 files changed

+28
-7
lines changed

lib/matplotlib/backends/backend_agg.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,9 @@ def buffer_rgba(self):
441441
"""
442442
return self.renderer.buffer_rgba()
443443

444-
def print_raw(self, filename_or_obj):
444+
def print_raw(self, filename_or_obj, *, metadata=None):
445+
if metadata is not None:
446+
raise ValueError("metadata not supported for raw/rgba")
445447
FigureCanvasAgg.draw(self)
446448
renderer = self.get_renderer()
447449
with cbook.open_file_cm(filename_or_obj, "wb") as fh:
@@ -518,22 +520,22 @@ def print_to_buffer(self):
518520
# print_figure(), and the latter ensures that `self.figure.dpi` already
519521
# matches the dpi kwarg (if any).
520522

521-
def print_jpg(self, filename_or_obj, *, pil_kwargs=None):
523+
def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
522524
# savefig() has already applied savefig.facecolor; we now set it to
523525
# white to make imsave() blend semi-transparent figures against an
524526
# assumed white background.
525527
with mpl.rc_context({"savefig.facecolor": "white"}):
526-
self._print_pil(filename_or_obj, "jpeg", pil_kwargs)
528+
self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)
527529

528530
print_jpeg = print_jpg
529531

530-
def print_tif(self, filename_or_obj, *, pil_kwargs=None):
531-
self._print_pil(filename_or_obj, "tiff", pil_kwargs)
532+
def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
533+
self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)
532534

533535
print_tiff = print_tif
534536

535-
def print_webp(self, filename_or_obj, *, pil_kwargs=None):
536-
self._print_pil(filename_or_obj, "webp", pil_kwargs)
537+
def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
538+
self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)
537539

538540
print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(
539541
"""

lib/matplotlib/figure.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3260,6 +3260,11 @@ def savefig(self, fname, *, transparent=None, **kwargs):
32603260
`~.FigureCanvasSVG.print_svg`.
32613261
- 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
32623262
3263+
Not supported for 'pgf', 'raw', and 'rgba' as those formats do not support
3264+
embedding metadata.
3265+
Does not currently support 'jpg', 'tiff', or 'webp', but may include
3266+
embedding EXIF metadata in the future.
3267+
32633268
bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox`
32643269
Bounding box in inches: only the given portion of the figure is
32653270
saved. If 'tight', try to figure out the tight bbox of the figure.

lib/matplotlib/image.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1610,6 +1610,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
16101610
Metadata in the image file. The supported keys depend on the output
16111611
format, see the documentation of the respective backends for more
16121612
information.
1613+
Currently only supported for "png", "pdf", "ps", "eps", and "svg".
16131614
pil_kwargs : dict, optional
16141615
Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo'
16151616
key is present, it completely overrides *metadata*, including the
@@ -1674,6 +1675,8 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
16741675
for k, v in metadata.items():
16751676
if v is not None:
16761677
pnginfo.add_text(k, v)
1678+
elif metadata is not None:
1679+
raise ValueError(f"metadata not supported for format {format!r}")
16771680
if format in ["jpg", "jpeg"]:
16781681
format = "jpeg" # Pillow doesn't recognize "jpg".
16791682
facecolor = mpl.rcParams["savefig.facecolor"]

lib/matplotlib/tests/test_figure.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1548,3 +1548,14 @@ def test_gridspec_no_mutate_input():
15481548
plt.subplots(1, 2, width_ratios=[1, 2], gridspec_kw=gs)
15491549
assert gs == gs_orig
15501550
plt.subplot_mosaic('AB', 6D4E width_ratios=[1, 2], gridspec_kw=gs)
1551+
1552+
1553+
@pytest.mark.parametrize('fmt', ['eps', 'pdf', 'png', 'ps', 'svg', 'svgz'])
1554+
def test_savefig_metadata(fmt):
1555+
Figure().savefig(io.BytesIO(), format=fmt, metadata={})
1556+
1557+
1558+
@pytest.mark.parametrize('fmt', ['jpeg', 'jpg', 'tif', 'tiff', 'webp', "raw", "rgba"])
1559+
def test_savefig_metadata_error(fmt):
1560+
with pytest.raises(ValueError, match="metadata not supported"):
1561+
Figure().savefig(io.BytesIO(), format=fmt, metadata={})

0 commit comments

Comments
 (0)
0