diff --git a/README.md b/README.md index 758cdbe..7991ecf 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,17 @@ Type "help", "copyright", "credits" or "license" for more information. You should see a plot! +### image mimetype support + +If you want to display a wider variety of objects using ipython's mimetype capturing, load our bundled ipython extension: + +```ipython +$ %load_ext itermplot.ipython +$ from PIL import Image +$ Image.open("my_cool_image.png") +# your image should be displayed +``` + ## Uninstall You can disable this backend by unsetting the `MPLBACKEND` environment variable. diff --git a/itermplot/__init__.py b/itermplot/__init__.py index f95de5c..4703bfe 100644 --- a/itermplot/__init__.py +++ b/itermplot/__init__.py @@ -83,7 +83,7 @@ def rev(c): return x -def imgcat(data, fn="plot.pdf"): +def imgcat(data: bytes, fn="plot.pdf"): """Output the image data to the iTerm2 console. If `lines` is greater than zero then advance the console `lines` number of blank lines, move back, and then output the image. This is the default behaviour if TMUX diff --git a/itermplot/ipython/__init__.py b/itermplot/ipython/__init__.py new file mode 100644 index 0000000..1f08e05 --- /dev/null +++ b/itermplot/ipython/__init__.py @@ -0,0 +1,39 @@ +""" +ipython extensions for image output handling. +e.g. + +```ipython +%load_ext itermplot.ipython +``` + +implemented based on https://ipython.readthedocs.io/en/stable/config/shell_mimerenderer.html +""" + +from .. import imgcat + + +def register_mimerenderer(ipython, mime, handler): + ipython.display_formatter.active_types.append(mime) + ipython.display_formatter.formatters[mime].enabled = True + ipython.mime_renderers[mime] = handler + + +def imgcat_factory(fn): + def _wrapper(img, _): + if isinstance(img, bytes): + return imgcat(img, fn=fn) + elif hasattr(img, "read"): + return imgcat(img.read(), fn=fn) + elif isinstance(img, str): + return imgcat(img.encode(), fn=fn) + else: + raise ValueError( + "imgcat only accepts bytes, file-like objects, and strings" + ) + + return _wrapper + + +def load_ipython_extension(ipython): + register_mimerenderer(ipython, "image/png", imgcat_factory(fn="img.png")) + register_mimerenderer(ipython, "image/jpeg", imgcat_factory(fn="img.jpg"))