ImageWin.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # a Windows DIB display interface
  6. #
  7. # History:
  8. # 1996-05-20 fl Created
  9. # 1996-09-20 fl Fixed subregion exposure
  10. # 1997-09-21 fl Added draw primitive (for tzPrint)
  11. # 2003-05-21 fl Added experimental Window/ImageWindow classes
  12. # 2003-09-05 fl Added fromstring/tostring methods
  13. #
  14. # Copyright (c) Secret Labs AB 1997-2003.
  15. # Copyright (c) Fredrik Lundh 1996-2003.
  16. #
  17. # See the README file for information on usage and redistribution.
  18. #
  19. from __future__ import annotations
  20. from . import Image
  21. class HDC:
  22. """
  23. Wraps an HDC integer. The resulting object can be passed to the
  24. :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
  25. methods.
  26. """
  27. def __init__(self, dc: int) -> None:
  28. self.dc = dc
  29. def __int__(self) -> int:
  30. return self.dc
  31. class HWND:
  32. """
  33. Wraps an HWND integer. The resulting object can be passed to the
  34. :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
  35. methods, instead of a DC.
  36. """
  37. def __init__(self, wnd: int) -> None:
  38. self.wnd = wnd
  39. def __int__(self) -> int:
  40. return self.wnd
  41. class Dib:
  42. """
  43. A Windows bitmap with the given mode and size. The mode can be one of "1",
  44. "L", "P", or "RGB".
  45. If the display requires a palette, this constructor creates a suitable
  46. palette and associates it with the image. For an "L" image, 128 graylevels
  47. are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
  48. with 20 graylevels.
  49. To make sure that palettes work properly under Windows, you must call the
  50. ``palette`` method upon certain events from Windows.
  51. :param image: Either a PIL image, or a mode string. If a mode string is
  52. used, a size must also be given. The mode can be one of "1",
  53. "L", "P", or "RGB".
  54. :param size: If the first argument is a mode string, this
  55. defines the size of the image.
  56. """
  57. def __init__(
  58. self, image: Image.Image | str, size: tuple[int, int] | None = None
  59. ) -> None:
  60. if isinstance(image, str):
  61. mode = image
  62. image = ""
  63. if size is None:
  64. msg = "If first argument is mode, size is required"
  65. raise ValueError(msg)
  66. else:
  67. mode = image.mode
  68. size = image.size
  69. if mode not in ["1", "L", "P", "RGB"]:
  70. mode = Image.getmodebase(mode)
  71. self.image = Image.core.display(mode, size)
  72. self.mode = mode
  73. self.size = size
  74. if image:
  75. assert not isinstance(image, str)
  76. self.paste(image)
  77. def expose(self, handle: int | HDC | HWND) -> None:
  78. """
  79. Copy the bitmap contents to a device context.
  80. :param handle: Device context (HDC), cast to a Python integer, or an
  81. HDC or HWND instance. In PythonWin, you can use
  82. ``CDC.GetHandleAttrib()`` to get a suitable handle.
  83. """
  84. handle_int = int(handle)
  85. if isinstance(handle, HWND):
  86. dc = self.image.getdc(handle_int)
  87. try:
  88. self.image.expose(dc)
  89. finally:
  90. self.image.releasedc(handle_int, dc)
  91. else:
  92. self.image.expose(handle_int)
  93. def draw(
  94. self,
  95. handle: int | HDC | HWND,
  96. dst: tuple[int, int, int, int],
  97. src: tuple[int, int, int, int] | None = None,
  98. ) -> None:
  99. """
  100. Same as expose, but allows you to specify where to draw the image, and
  101. what part of it to draw.
  102. The destination and source areas are given as 4-tuple rectangles. If
  103. the source is omitted, the entire image is copied. If the source and
  104. the destination have different sizes, the image is resized as
  105. necessary.
  106. """
  107. if src is None:
  108. src = (0, 0) + self.size
  109. handle_int = int(handle)
  110. if isinstance(handle, HWND):
  111. dc = self.image.getdc(handle_int)
  112. try:
  113. self.image.draw(dc, dst, src)
  114. finally:
  115. self.image.releasedc(handle_int, dc)
  116. else:
  117. self.image.draw(handle_int, dst, src)
  118. def query_palette(self, handle: int | HDC | HWND) -> int:
  119. """
  120. Installs the palette associated with the image in the given device
  121. context.
  122. This method should be called upon **QUERYNEWPALETTE** and
  123. **PALETTECHANGED** events from Windows. If this method returns a
  124. non-zero value, one or more display palette entries were changed, and
  125. the image should be redrawn.
  126. :param handle: Device context (HDC), cast to a Python integer, or an
  127. HDC or HWND instance.
  128. :return: The number of entries that were changed (if one or more entries,
  129. this indicates that the image should be redrawn).
  130. """
  131. handle_int = int(handle)
  132. if isinstance(handle, HWND):
  133. handle = self.image.getdc(handle_int)
  134. try:
  135. result = self.image.query_palette(handle)
  136. finally:
  137. self.image.releasedc(handle, handle)
  138. else:
  139. result = self.image.query_palette(handle_int)
  140. return result
  141. def paste(
  142. self, im: Image.Image, box: tuple[int, int, int, int] | None = None
  143. ) -> None:
  144. """
  145. Paste a PIL image into the bitmap image.
  146. :param im: A PIL image. The size must match the target region.
  147. If the mode does not match, the image is converted to the
  148. mode of the bitmap image.
  149. :param box: A 4-tuple defining the left, upper, right, and
  150. lower pixel coordinate. See :ref:`coordinate-system`. If
  151. None is given instead of a tuple, all of the image is
  152. assumed.
  153. """
  154. im.load()
  155. if self.mode != im.mode:
  156. im = im.convert(self.mode)
  157. if box:
  158. self.image.paste(im.im, box)
  159. else:
  160. self.image.paste(im.im)
  161. def frombytes(self, buffer: bytes) -> None:
  162. """
  163. Load display memory contents from byte data.
  164. :param buffer: A buffer containing display data (usually
  165. data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
  166. """
  167. self.image.frombytes(buffer)
  168. def tobytes(self) -> bytes:
  169. """
  170. Copy display memory contents to bytes object.
  171. :return: A bytes object containing display data.
  172. """
  173. return self.image.tobytes()
  174. class Window:
  175. """Create a Window with the given title size."""
  176. def __init__(
  177. self, title: str = "PIL", width: int | None = None, height: int | None = None
  178. ) -> None:
  179. self.hwnd = Image.core.createwindow(
  180. title, self.__dispatcher, width or 0, height or 0
  181. )
  182. def __dispatcher(self, action: str, *args: int) -> None:
  183. getattr(self, f"ui_handle_{action}")(*args)
  184. def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
  185. pass
  186. def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None:
  187. pass
  188. def ui_handle_destroy(self) -> None:
  189. pass
  190. def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
  191. pass
  192. def ui_handle_resize(self, width: int, height: int) -> None:
  193. pass
  194. def mainloop(self) -> None:
  195. Image.core.eventloop()
  196. class ImageWindow(Window):
  197. """Create an image window which displays the given image."""
  198. def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None:
  199. if not isinstance(image, Dib):
  200. image = Dib(image)
  201. self.image = image
  202. width, height = image.size
  203. super().__init__(title, width=width, height=height)
  204. def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
  205. self.image.draw(dc, (x0, y0, x1, y1))