interactive_image.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from __future__ import annotations
  2. import time
  3. from pathlib import Path
  4. from typing import Any, Callable, List, Optional, Union, cast
  5. from PIL.Image import Image as PIL_Image
  6. from ..events import GenericEventArguments, MouseEventArguments, handle_event
  7. from .image import pil_to_base64
  8. from .mixins.content_element import ContentElement
  9. from .mixins.source_element import SourceElement
  10. class InteractiveImage(SourceElement, ContentElement, component='interactive_image.js'):
  11. CONTENT_PROP = 'content'
  12. PIL_CONVERT_FORMAT = 'PNG'
  13. def __init__(self,
  14. source: Union[str, Path] = '', *,
  15. content: str = '',
  16. on_mouse: Optional[Callable[..., Any]] = None,
  17. events: List[str] = ['click'],
  18. cross: bool = False,
  19. ) -> None:
  20. """Interactive Image
  21. Create an image with an SVG overlay that handles mouse events and yields image coordinates.
  22. It is also the best choice for non-flickering image updates.
  23. If the source URL changes faster than images can be loaded by the browser, some images are simply skipped.
  24. Thereby repeatedly updating the image source will automatically adapt to the available bandwidth.
  25. See `OpenCV Webcam <https://github.com/zauberzeug/nicegui/tree/main/examples/opencv_webcam/main.py>`_ for an example.
  26. :param source: the source of the image; can be an URL, local file path or a base64 string
  27. :param content: SVG content which should be overlaid; viewport has the same dimensions as the image
  28. :param on_mouse: callback for mouse events (yields `type`, `image_x` and `image_y`)
  29. :param events: list of JavaScript events to subscribe to (default: `['click']`)
  30. :param cross: whether to show crosshairs (default: `False`)
  31. """
  32. super().__init__(source=source, content=content)
  33. self._props['events'] = events
  34. self._props['cross'] = cross
  35. def handle_mouse(e: GenericEventArguments) -> None:
  36. if on_mouse is None:
  37. return
  38. args = cast(dict, e.args)
  39. arguments = MouseEventArguments(
  40. sender=self,
  41. client=self.client,
  42. type=args.get('mouse_event_type', ''),
  43. image_x=args.get('image_x', 0.0),
  44. image_y=args.get('image_y', 0.0),
  45. button=args.get('button', 0),
  46. buttons=args.get('buttons', 0),
  47. alt=args.get('alt', False),
  48. ctrl=args.get('ctrl', False),
  49. meta=args.get('meta', False),
  50. shift=args.get('shift', False),
  51. )
  52. handle_event(on_mouse, arguments)
  53. self.on('mouse', handle_mouse)
  54. def _set_props(self, source: Union[str, Path]) -> None:
  55. if isinstance(source, PIL_Image):
  56. source = pil_to_base64(source, self.PIL_CONVERT_FORMAT)
  57. super()._set_props(source)
  58. def force_reload(self) -> None:
  59. """Force the image to reload from the source."""
  60. self._props['t'] = time.time()
  61. self.update()