Skip to content

Commit

Permalink
Handle exceptions in _repr_jpeg_ and _repr_png_
Browse files Browse the repository at this point in the history
In 10.0.0 a _repr_jpeg_ implementation was added to the Image object to
enable the use of display_jpeg() in IPython environments. However, in
some cases the implementation of this method could result in an
exception being raised while trying to generate the jpeg data. The best
example is if the image data is in an RGBA format as a result of the
object being created by opening a PNG file. In this case trying to save
the Image object as a jpeg will error because the jpeg format can't
represent the transparency in the alpha channel. This results in an
exception being raised in the IPython/Jupyter context when outputing the
image object. However, in cases like this IPython allows the repr
methods to return None to indicate there is no representation in that
format available. [1] This commit updates the _repr_png_ and _repr_jpeg_
methods to catch any exception that might be raised while trying to
generate the image data. If an exception is raised we treat that as not
being able to generate image data in that format and return None
instead.

Related to python-pillow#7259

[1] https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods
  • Loading branch information
mtreinish committed Jul 6, 2023
1 parent f089c2d commit 6d440ac
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,14 +651,20 @@ def _repr_png_(self):
:returns: PNG version of the image as bytes
"""
return self._repr_image("PNG", compress_level=1)
try:
return self._repr_image("PNG", compress_level=1)
except Exception:
return None

def _repr_jpeg_(self):
"""iPython display hook support for JPEG format.
:returns: JPEG version of the image as bytes
"""
return self._repr_image("JPEG")
try:
self._repr_image("JPEG")
except Exception:
return None

@property
def __array_interface__(self):
Expand Down

0 comments on commit 6d440ac

Please sign in to comment.