add _repr_jpg_ for ipython display

Signed-off-by: Ishant Mrinal Haloi <mrinal.haloi11@gmail.com>
This commit is contained in:
Ishant Mrinal Haloi 2023-05-04 21:43:57 +05:30
parent b073a8962b
commit 5377b0735f
2 changed files with 33 additions and 3 deletions

View File

@ -922,6 +922,19 @@ class TestFileJpeg:
im.load() im.load()
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
def test_repr_jpg(self):
im = hopper()
with Image.open(BytesIO(im._repr_jpg_())) as repr_jpg:
assert repr_jpg.format == "JPEG"
assert_image_equal(im, repr_jpg)
def test_repr_jpg_error(self):
im = hopper("F")
with pytest.raises(ValueError):
im._repr_jpg_()
@pytest.mark.skipif(not is_win32(), reason="Windows only") @pytest.mark.skipif(not is_win32(), reason="Windows only")
@skip_unless_feature("jpg") @skip_unless_feature("jpg")

View File

@ -633,19 +633,36 @@ class Image:
) )
) )
def _repr_png_(self): def _repr_image(self, format):
"""iPython display hook support """iPython display hook support
:param format: Image format.
:returns: png version of the image as bytes :returns: png version of the image as bytes
""" """
b = io.BytesIO() b = io.BytesIO()
try: try:
self.save(b, "PNG") self.save(b, format)
except Exception as e: except Exception as e:
msg = "Could not save to PNG for display" msg = f"Could not save to {format} for display"
raise ValueError(msg) from e raise ValueError(msg) from e
return b.getvalue() return b.getvalue()
def _repr_png_(self):
"""iPython display hook support for PNG format.
:returns: png version of the image as bytes
"""
return self._repr_image("PNG")
def _repr_jpg_(self):
"""iPython display hook support for JPEG format.
:returns: jpg version of the image as bytes
"""
return self._repr_image("JPEG")
_repr_jpeg_ = _repr_jpg_
@property @property
def __array_interface__(self): def __array_interface__(self):
# numpy array interface support # numpy array interface support