Skip to content

Commit

Permalink
make image format configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
falkoschindler committed Nov 23, 2023
1 parent 07c60aa commit 5dc3e99
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
7 changes: 4 additions & 3 deletions nicegui/elements/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@


class Image(SourceElement, component='image.js'):
PIL_CONVERT_FORMAT = 'PNG'

def __init__(self, source: Union[str, Path, PIL_Image] = '') -> None:
"""Image
Expand All @@ -23,7 +24,7 @@ def __init__(self, source: Union[str, Path, PIL_Image] = '') -> None:

def _set_props(self, source: Union[str, Path]) -> None:
if isinstance(source, PIL_Image):
source = image_to_base64(source)
source = pil_to_base64(source, self.PIL_CONVERT_FORMAT)
super()._set_props(source)

def force_reload(self) -> None:
Expand All @@ -32,11 +33,11 @@ def force_reload(self) -> None:
self.update()


def image_to_base64(pil_image: PIL_Image, image_format: str = 'PNG') -> str:
def pil_to_base64(pil_image: PIL_Image, image_format: str) -> str:
"""Convert a PIL image to a base64 string which can be used as image source.
:param pil_image: the PIL image
:param image_format: the image format (default: 'PNG')
:param image_format: the image format
:return: the base64 string
"""
buffer = io.BytesIO()
Expand Down
5 changes: 3 additions & 2 deletions nicegui/elements/interactive_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
from PIL.Image import Image as PIL_Image

from ..events import GenericEventArguments, MouseEventArguments, handle_event
from .image import image_to_base64
from .image import pil_to_base64
from .mixins.content_element import ContentElement
from .mixins.source_element import SourceElement


class InteractiveImage(SourceElement, ContentElement, component='interactive_image.js'):
CONTENT_PROP = 'content'
PIL_CONVERT_FORMAT = 'PNG'

def __init__(self,
source: Union[str, Path] = '', *,
Expand Down Expand Up @@ -62,7 +63,7 @@ def handle_mouse(e: GenericEventArguments) -> None:

def _set_props(self, source: Union[str, Path]) -> None:
if isinstance(source, PIL_Image):
source = image_to_base64(source)
source = pil_to_base64(source, self.PIL_CONVERT_FORMAT)
super()._set_props(source)

def force_reload(self) -> None:
Expand Down

0 comments on commit 5dc3e99

Please sign in to comment.