Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: support loading image from path (#555)

Akshay Agrawal41a6959ea78f
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index 703559de9e..98db97e7f8 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import io
+import os
from typing import Any, Optional, Union
import marimo._output.data.data as mo_data
@@ -23,9 +24,15 @@ def image(
) -> Html:
"""Render an image as HTML.
- **Example.**
+ **Examples.**
```python3
+ # Render an image from a local file
+ mo.image(src="path/to/image.png")
+ ```
+
+ ```python3
+ # Render an image from a URL
mo.image(
src="https://marimo.io/logo.png",
alt="Marimo logo",
@@ -33,14 +40,12 @@ def image(
height=100,
rounded=True,
)
-
- with open("logo.png", "rb") as file:
- mo.image(src=file)
```
**Args.**
- - `src`: the URL of the image or a file-like object
+ - `src`: a path or URL to an image, or a file-like object
+ (opened in binary mode)
- `alt`: the alt text of the image
- `width`: the width of the image in pixels
- `height`: the height of the image in pixels
@@ -58,6 +63,11 @@ def image(
resolved_src = mo_data.image(src.read()).url
elif isinstance(src, bytes):
resolved_src = mo_data.image(src).url
+ elif isinstance(src, str) and os.path.isfile(src):
+ with open(src, "rb") as f:
+ resolved_src = mo_data.image(
+ f.read(), ext=os.path.splitext(src)[1]
+ ).url
else:
resolved_src = io_to_data_url(src, fallback_mime_type="image/png")
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index ed699e4c1e..897b512328 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -1,4 +1,8 @@
# Copyright 2023 Marimo. All rights reserved.
+import sys
+
+import pytest
+
from marimo._plugins.stateless.image import image
from marimo._runtime.context import get_context
from marimo._runtime.runtime import Kernel
@@ -60,3 +64,22 @@ def test_image_str(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 0
+
+
+# TODO(akshayka): Debug on Windows
[email protected](sys.platform == "win32", reason="Failing on Windows CI")
+def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:
+ # Just opens a file that exists, and make sure it gets registered
+ # in the virtual path registry
+ with open(__file__, encoding="utf-8") as f:
+ k.run(
+ [
+ exec_req.get(
+ f"""
+ import marimo as mo
+ image = mo.image('{f.name}')
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1