manzt
manzt•2mo ago

View a local image (png/jpeg)

Is there a simple way to view local images (e.g., JPEG/PNG) in a reactive cell? I found https://docs.marimo.io/guides/integrating_with_marimo/displaying_objects.html, but this seems for remote urls? I guess I could base64 encode the images and create data urls. Just curious if I missed something in the docs.
Solution:
@manzt , you should be able to use mo.image() that supports local paths, remote urls, and bytes
Jump to solution
5 Replies
manzt
manztOP•2mo ago
import base64

class MyImage:
def __init__(self, fp: pathlib.Path) -> None:
self._url = f"data:image/jpeg;base64,{base64.encodebytes(fp.read_bytes()).decode("utf-8")}"

def _mime_(self) -> tuple[str, str]:
return ("image/jpeg", self._url)

MyImage(picker.value)
import base64

class MyImage:
def __init__(self, fp: pathlib.Path) -> None:
self._url = f"data:image/jpeg;base64,{base64.encodebytes(fp.read_bytes()).decode("utf-8")}"

def _mime_(self) -> tuple[str, str]:
return ("image/jpeg", self._url)

MyImage(picker.value)
seems to work! Any way to constrain the width?
Solution
Myles Scolnick
Myles Scolnick•2mo ago
@manzt , you should be able to use mo.image() that supports local paths, remote urls, and bytes
Myles Scolnick
Myles Scolnick•2mo ago
for width. can you might be able to do mo.img().style({"width": 300})
manzt
manztOP•2mo ago
heck ya, I also go there with mo.Html... but this is cleaner 🙂
Traceback (most recent call last): File "/Users/manzt/.cache/uv/archive-v0/DCgM2WuQ6B8IEZg0HzEjf/lib/python3.12/site-packages/marimo/_runtime/executor.py", line 171, in execute_cell return eval(cell.last_expr, glbls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cell marimo://demo.py#cell=cell-5 , line 1, in <module> mo.img(fp) ^^^^^^ AttributeError: module 'marimo' has no attribute 'img'
hmm, maybe a different namespace? ahh mo.image()
Myles Scolnick
Myles Scolnick•2mo ago
Oh oops sorry for the typo