瀏覽代碼

make image format configurable

Falko Schindler 1 年之前
父節點
當前提交
5dc3e99e53
共有 2 個文件被更改,包括 7 次插入5 次删除
  1. 4 3
      nicegui/elements/image.py
  2. 3 2
      nicegui/elements/interactive_image.py

+ 4 - 3
nicegui/elements/image.py

@@ -10,6 +10,7 @@ from .mixins.source_element import SourceElement
 
 
 class Image(SourceElement, component='image.js'):
+    PIL_CONVERT_FORMAT = 'PNG'
 
     def __init__(self, source: Union[str, Path, PIL_Image] = '') -> None:
         """Image
@@ -23,7 +24,7 @@ class Image(SourceElement, component='image.js'):
 
     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:
@@ -32,11 +33,11 @@ class Image(SourceElement, component='image.js'):
         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()

+ 3 - 2
nicegui/elements/interactive_image.py

@@ -7,13 +7,14 @@ from typing import Any, Callable, List, Optional, Union, cast
 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] = '', *,
@@ -62,7 +63,7 @@ class InteractiveImage(SourceElement, ContentElement, component='interactive_ima
 
     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: