Search code examples
pythonimagewidgetipywidgets

How to put image retrieved from url into an image widget


I found this code and it works fine. The image can be retrieved and displayed.

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

However, I actually want to put the image into an image widget, so I have tried this:

import IPython
from ipywidgets import widgets

url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
image = IPython.display.Image(url, width = 300)

widgets.Image(
  value=image,
  format='jpg', 
  width=300,
  height=400,
)

But I got this error:

---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-45-5011b6084128> in <module>()
     57     format='jpg',
     58     width=300,
---> 59     height=400,
     60 )

________________________________________
7 frames
________________________________________
/usr/local/lib/python3.6/dist-packages/traitlets/traitlets.py in error(self, obj, value)
    623             e = "The '%s' trait must be %s, but a value of %r was specified." \
    624                 % (self.name, self.info(), repr_type(value))
--> 625         raise TraitError(e)
    626 
    627     def get_metadata(self, key, default=None):

TraitError: The 'value' trait of an Image instance must be a bytes object, but a value of 
<IPython.core.display.Image object> <class 'IPython.core.display.Image'> was specified.

So, my question is: how can I put the image into an image widget?


Solution

  • Firstly thanks for your minimal example.

    The error tells you what you need to do. You need to pass the bytes of the image file to the ipywidgets.Image class. Do this by passing image.data from your Ipython.display.Image instance.

    import IPython
    from ipywidgets import widgets
    
    url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
    image = IPython.display.Image(url, width = 300)
    
    widgets.Image(
      value=image.data,
      format='jpg', 
      width=300,
      height=400,
    )
    

    Alternatively, use a package like requests to get the bytes of the image and pass them to widgets.Image, without the need for the Ipython.display.Image instance.