-
-
Notifications
You must be signed in to change notification settings - Fork 665
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e9c5824
commit 07c60aa
Showing
3 changed files
with
44 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,46 @@ | ||
import base64 | ||
import io | ||
import time | ||
from pathlib import Path | ||
from typing import Union | ||
|
||
from PIL.Image import Image as PIL_Image | ||
|
||
from .mixins.source_element import SourceElement | ||
|
||
|
||
class Image(SourceElement, component='image.js'): | ||
|
||
def __init__(self, source: Union[str, Path] = '') -> None: | ||
def __init__(self, source: Union[str, Path, PIL_Image] = '') -> None: | ||
"""Image | ||
Displays an image. | ||
This element is based on Quasar's `QImg <https://quasar.dev/vue-components/img>`_ component. | ||
:param source: the source of the image; can be a URL, local file path or a base64 string | ||
:param source: the source of the image; can be a URL, local file path, a base64 string or a PIL image | ||
""" | ||
super().__init__(source=source) | ||
|
||
def _set_props(self, source: Union[str, Path]) -> None: | ||
if isinstance(source, PIL_Image): | ||
source = image_to_base64(source) | ||
super()._set_props(source) | ||
|
||
def force_reload(self) -> None: | ||
"""Force the image to reload from the source.""" | ||
self._props['t'] = time.time() | ||
self.update() | ||
|
||
|
||
def image_to_base64(pil_image: PIL_Image, image_format: str = 'PNG') -> 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') | ||
:return: the base64 string | ||
""" | ||
buffer = io.BytesIO() | ||
pil_image.save(buffer, image_format) | ||
base64_encoded = base64.b64encode(buffer.getvalue()) | ||
base64_string = base64_encoded.decode('utf-8') | ||
return f'data:image/{image_format.lower()};base64,{base64_string}' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters