jupyter-widgets / ipywidgets

Interactive Widgets for the Jupyter Notebook

Home Page:https://ipywidgets.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Convert widget into image of type "image/jpeg" based on event

kolibril13 opened this issue · comments

Hi there!

When I share a notebook with colleagues, it would be great if they could directly see an image of the widget.

Currently, a widget would be displayed like Image(value=b'\xff\xd8\xff\xe0\x00\x10JFIF ... when reopening the notebook or displaying it on GitHub.
Code example:

import requests
response = requests.get("https://github.com/Octoframes/jupyter_capture_output/blob/main/assets/cute_dog.jpg?raw=true")

import ipywidgets
ipywidgets.Image(value = response.content,  format='jpg', width=500)

In order to display the actual content of the image, I can add the mimebundle["image/jpeg"] = encoded_image like this:

import ipywidgets
import requests
response = requests.get("https://github.com/Octoframes/jupyter_capture_output/blob/main/assets/cute_dog.jpg?raw=true")


class MyImageWidget(ipywidgets.Image):
    def _repr_mimebundle_(self, *args, **kwargs):
        mimebundle = super()._repr_mimebundle_(*args, **kwargs)
        import base64
        encoded_image = base64.encodebytes(self.value).decode("utf-8")
        mimebundle["image/jpeg"] = encoded_image
        metadata = {"image/jpeg": {"width": self.width}}
        return mimebundle, metadata
MyImageWidget(value = response.content,  format='jpg', width="500px")
image

but this would make the image static directly.

It would be great to make a widget static based on an event after all interaction is done.

This event could e.g. be a button like this one:

button_value = False
import ipywidgets

button = ipywidgets.Button(description = "Embed me!")

def on_button_clicked(b):
    button_value = True
    b.description = "True"

button.on_click(on_button_clicked)
display(button)

I'm grateful for any ideas on how to convert a widget into a static image based on an event :)

cc. @stevejpurves, you might be interested in this feature as well for Myst-markdown documents.

This issue is related to manzt/anywidget#396 .