Display webp images

Hi guys,
I wanted to know if webp images were supported by panel.
I’ve seen the pn.pane.JPG/PNG thing, But there does not seem to be an equivalent for the webp format.

Thanks in advance.

1 Like

Hi @Adam

Something like the below could get you started depending on the use case.

import panel as pn
from panel.pane.image import ImageBase

pn.extension(sizing_mode="stretch_width", template="fast")

webp_url = "https://www.gstatic.com/webp/gallery/1.webp"

def to_webp_pane(url: str, height=500, width=500, **params):
    if url.startswith("http"):
        object = f"""<img style="height: {height}px, width: {width}px" src="{url}" alt="WebP rules.">"""
    else:
        raise NotImplementedError()
    
    return pn.pane.HTML(object, height=height, width=width, **params)

to_webp_pane(webp_url, height=370, width=550).servable()

class WEBP(ImageBase):

    filetype = 'webp'

    @classmethod
    def _imgshape(cls, data):
        import struct
        print(data[0:100])
        w, h = struct.unpack('>LL', data[16:24])
        return int(w), int(h)

WEBP(webp_url, height=370, width=550).servable()

accent="#bc5090"
pn.state.template.param.update(title="WEBP Images", accent_base_color=accent, header_background=accent)

The second method WEBP is the most general. But somebody needs to figure out how w, h = struct.unpack('>LL', data[16:24]) should be adjusted to always return the correct width and height of the image. I don’t know how.

If you want this supported natively in Panel please create a Feature Request on Github.

It would definitely be good to add webp support, but it would indeed take some investigation to get a reliable way to extract the width and height and to detect them automatically without loading a library when they aren’t detected. A github issue would be appreciated!