From fdce8453645c95c347660887077de87fa6650571 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 27 Dec 2020 15:36:16 +1100 Subject: [PATCH] Added exception explaining that _repr_png_ saves to PNG --- Tests/test_file_png.py | 6 ++++++ src/PIL/Image.py | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py index 80305c7b406..9028aaf23b9 100644 --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -537,6 +537,12 @@ def test_repr_png(self): assert repr_png.format == "PNG" assert_image_equal(im, repr_png) + def test_repr_png_error(self): + im = hopper("F") + + with pytest.raises(ValueError): + im._repr_png_() + def test_chunk_order(self, tmp_path): with Image.open("Tests/images/icc_profile.png") as im: test_file = str(tmp_path / "temp.png") diff --git a/src/PIL/Image.py b/src/PIL/Image.py index ae2559d11de..e9d4e4f29ba 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -670,7 +670,10 @@ def _repr_png_(self): :returns: png version of the image as bytes """ b = io.BytesIO() - self.save(b, "PNG") + try: + self.save(b, "PNG") + except Exception as e: + raise ValueError("Could not save to PNG for display") from e return b.getvalue() @property