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 b8b840651a6..1b4efdc4fbc 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