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.

fix: PIL.Image in mo.image() (#4483)

Myles Scolnick27b94dd86dba
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index a4c048051c..bcbf4420e2 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -74,6 +74,17 @@ def _normalize_image(src: ImageLike) -> Image:
normalized_src: Image = io.BytesIO()
img.save(normalized_src, format="PNG")
return normalized_src
+
+ # Handle PIL Image objects
+ if DependencyManager.pillow.imported():
+ from PIL import Image as _Image
+
+ if isinstance(src, _Image.Image):
+ img_byte_arr = io.BytesIO()
+ src.save(img_byte_arr, format=src.format or "PNG")
+ img_byte_arr.seek(0)
+ return img_byte_arr
+
# Verify that this is a image object
if not isinstance(src, (str, bytes, io.BytesIO, io.BufferedReader, Path)):
raise ValueError(
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index ab68aff7aa..90662accf0 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -1,7 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import io
import sys
+from typing import TYPE_CHECKING
import pytest
@@ -13,6 +15,9 @@ from tests.conftest import ExecReqProvider
HAS_DEPS = DependencyManager.numpy.has() and DependencyManager.pillow.has()
+if TYPE_CHECKING:
+ from pathlib import Path
+
async def test_image() -> None:
result = image(
@@ -170,3 +175,37 @@ async def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
+
+
+def test_image_constructor(tmp_path: Path):
+ # BytesIO
+ result = image(
+ io.BytesIO(b"hello"),
+ )
+ assert result.text.startswith("<img src='data:image/png;base64,")
+ # Bytes
+ result = image(
+ io.BytesIO(b"hello").getvalue(),
+ )
+ assert result.text.startswith("<img src='data:image/png;base64,")
+ # String
+ result = image(
+ "https://marimo.io/logo.png",
+ )
+ assert result.text.startswith("<img src='https://marimo.io/logo.png' />")
+ # Path
+ img_path = tmp_path / "test.png"
+ img_path.touch()
+ result = image(img_path)
+ assert result.text.startswith("<img src='data:image/png;base64,")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_image_constructor_pil():
+ from PIL import Image
+
+ # PIL Image
+ result = image(
+ Image.new("RGB", (100, 100), color="red"),
+ )
+ assert result.text.startswith("<img src='data:image/png;base64,")