IPython.display.Image arguments

In [1]:
from IPython.display import Image

IPython's Image display object takes three kinds of arguments

  1. raw image data (e.g. the results of open(filename).read()
In [2]:
with open("Graphs/graph.png") as f:
    data = f.read()
Image(data=data)
Out[2]:

The second model is to load an image from a filename. This is functionally the same as above, but IPython does the reading from the file:

In [3]:
Image(filename="Graphs/graph.png")
Out[3]:

The third form is passing URLs. Absolute URLs can be used, but relative URLs will be served relative to the notebook's own directory:

In [4]:
Image(url="Graphs/graph.png")
Out[4]:

This looks the same as above, but instead of embedding the image data in the notebook document itself, it just links to the image:

In [5]:
Image(url="Graphs/graph.png")._repr_html_()
Out[5]:
u'<img src="Graphs/graph.png"/>'

Where this can get confusing is if you don't tell IPython which one of these you are specifying, and you just pass the one argument positionally:

In [6]:
Image("Graphs/graph.png")
Out[6]:

IPython tries to guess what you mean in this case:

  1. if it looks like a path and points to an existing file, use it as a filename
  2. if it looks like a URL, use it as a URL
  3. otherwise, fallback on

That #3 is the source of the most confusion. If you pass it a filename that doesn't exist, you will get a broken image:

In [7]:
Image("/Graphs/graph.png")
Out[7]:
In [8]:
Image("/Graphs/graph.png")._repr_png_()
Out[8]:
'/Graphs/graph.png'

which is obviously not valid PNG data.

Note that URLs to files must be relative. Absolute URLs will generally be wrong:

In [9]:
Image(url="/Graphs/graph.png")
Out[9]: