[IPython-User] PIL Display Hooks

MinRK benjaminrk@gmail....
Thu Mar 15 19:40:08 CDT 2012


This should do it:

from IPython.core import display
from io import BytesIO

def display_pil_image(im):
    """displayhook function for PIL Images, rendered as PNG"""

    b = BytesIO()
    im.save(b, format='png')
    data = b.getvalue()

    ip_img = display.Image(data=data, format='png', embed=True)
    return ip_img._repr_png_()


# register display func with PNG formatter:
png_formatter = get_ipython().display_formatter.formatters['image/png']
png_formatter.for_type(Image.Image, display_pil_image)

And now the default repr of PIL Images will be to render them as PNGs.

It seems like this (or something like it -PIL's class structure is a
bit funky) should perhaps be on by default.

-MinRK

On Thu, Mar 15, 2012 at 14:21, Brian Granger <ellisonbg@gmail.com> wrote:
> It should definitely be possible to do this.  Here is what I would advise:
>
> * Look into generating raw JPEG/PNG data from an image.  You could
> write this to a file and then read it back in, or possible write
> straight to a python bytes object.
> * Then look into IPython's display protocol.  The best resource on
> this is the display_protocol.ipynb example notebook in
> IPython/docs/examples/notebooks.
>
> Once you have the raw JPEG, it shouldn't be more than a few lines of
> code to hook into the IPython display system.  Once that is done
> images will "just work" in the Notebook.
>
> Cheers,
>
> Brian
>
> On Thu, Mar 15, 2012 at 1:38 PM, Michael Hadmack <hadmack@gmail.com> wrote:
>> Does anyone know if it is possible to display PIL objects inline in a
>> notebook?  It would be nice it these displayed the same way as
>> Matplotlib objects.  I cannot find a way to get raw image data out of
>> a PIL.Image object right now.  Looks like you can only save to a file
>> or file object.  I can't remember right now how to create a file
>> object that is just a memory buffer, don't know if this would do the
>> trick.
>>
>> -Mike
>> _______________________________________________
>> IPython-User mailing list
>> IPython-User@scipy.org
>> http://mail.scipy.org/mailman/listinfo/ipython-user
>
>
>
> --
> Brian E. Granger
> Cal Poly State University, San Luis Obispo
> bgranger@calpoly.edu and ellisonbg@gmail.com
> _______________________________________________
> IPython-User mailing list
> IPython-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/ipython-user


More information about the IPython-User mailing list