ImageDraw2.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # WCK-style drawing interface operations
  6. #
  7. # History:
  8. # 2003-12-07 fl created
  9. # 2005-05-15 fl updated; added to PIL as ImageDraw2
  10. # 2005-05-15 fl added text support
  11. # 2005-05-20 fl added arc/chord/pieslice support
  12. #
  13. # Copyright (c) 2003-2005 by Secret Labs AB
  14. # Copyright (c) 2003-2005 by Fredrik Lundh
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. """
  19. (Experimental) WCK-style drawing interface operations
  20. .. seealso:: :py:mod:`PIL.ImageDraw`
  21. """
  22. from __future__ import annotations
  23. from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
  24. TYPE_CHECKING = False
  25. if TYPE_CHECKING:
  26. from typing import Any, AnyStr, BinaryIO
  27. from ._typing import Coords, StrOrBytesPath
  28. class Pen:
  29. """Stores an outline color and width.
  30. :param color: The outline color.
  31. :param width: The line width, in pixels.
  32. """
  33. def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
  34. self.color = ImageColor.getrgb(color)
  35. self.width = width
  36. class Brush:
  37. """Stores a fill color"""
  38. def __init__(self, color: str, opacity: int = 255) -> None:
  39. self.color = ImageColor.getrgb(color)
  40. class Font:
  41. """Stores a TrueType font and color"""
  42. def __init__(
  43. self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
  44. ) -> None:
  45. # FIXME: add support for bitmap fonts
  46. self.color = ImageColor.getrgb(color)
  47. self.font = ImageFont.truetype(file, size)
  48. class Draw:
  49. """
  50. (Experimental) WCK-style drawing interface
  51. """
  52. def __init__(
  53. self,
  54. image: Image.Image | str,
  55. size: tuple[int, int] | list[int] | None = None,
  56. color: float | tuple[float, ...] | str | None = None,
  57. ) -> None:
  58. if isinstance(image, str):
  59. if size is None:
  60. msg = "If image argument is mode string, size must be a list or tuple"
  61. raise ValueError(msg)
  62. image = Image.new(image, size, color)
  63. self.draw = ImageDraw.Draw(image)
  64. self.image = image
  65. self.transform: tuple[float, float, float, float, float, float] | None = None
  66. def flush(self) -> Image.Image:
  67. return self.image
  68. def render(
  69. self,
  70. op: str,
  71. xy: Coords,
  72. pen: Pen | Brush | None,
  73. brush: Brush | Pen | None = None,
  74. **kwargs: Any,
  75. ) -> None:
  76. # handle color arguments
  77. outline = fill = None
  78. width = 1
  79. if isinstance(pen, Pen):
  80. outline = pen.color
  81. width = pen.width
  82. elif isinstance(brush, Pen):
  83. outline = brush.color
  84. width = brush.width
  85. if isinstance(brush, Brush):
  86. fill = brush.color
  87. elif isinstance(pen, Brush):
  88. fill = pen.color
  89. # handle transformation
  90. if self.transform:
  91. path = ImagePath.Path(xy)
  92. path.transform(self.transform)
  93. xy = path
  94. # render the item
  95. if op in ("arc", "line"):
  96. kwargs.setdefault("fill", outline)
  97. else:
  98. kwargs.setdefault("fill", fill)
  99. kwargs.setdefault("outline", outline)
  100. kwargs.setdefault("width", width)
  101. getattr(self.draw, op)(xy, **kwargs)
  102. def settransform(self, offset: tuple[float, float]) -> None:
  103. """Sets a transformation offset."""
  104. xoffset, yoffset = offset
  105. self.transform = (1, 0, xoffset, 0, 1, yoffset)
  106. def arc(
  107. self,
  108. xy: Coords,
  109. pen: Pen | Brush | None,
  110. start: float,
  111. end: float,
  112. *options: Any,
  113. ) -> None:
  114. """
  115. Draws an arc (a portion of a circle outline) between the start and end
  116. angles, inside the given bounding box.
  117. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
  118. """
  119. self.render("arc", xy, pen, *options, start=start, end=end)
  120. def chord(
  121. self,
  122. xy: Coords,
  123. pen: Pen | Brush | None,
  124. start: float,
  125. end: float,
  126. *options: Any,
  127. ) -> None:
  128. """
  129. Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
  130. with a straight line.
  131. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
  132. """
  133. self.render("chord", xy, pen, *options, start=start, end=end)
  134. def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
  135. """
  136. Draws an ellipse inside the given bounding box.
  137. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
  138. """
  139. self.render("ellipse", xy, pen, *options)
  140. def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
  141. """
  142. Draws a line between the coordinates in the ``xy`` list.
  143. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
  144. """
  145. self.render("line", xy, pen, *options)
  146. def pieslice(
  147. self,
  148. xy: Coords,
  149. pen: Pen | Brush | None,
  150. start: float,
  151. end: float,
  152. *options: Any,
  153. ) -> None:
  154. """
  155. Same as arc, but also draws straight lines between the end points and the
  156. center of the bounding box.
  157. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
  158. """
  159. self.render("pieslice", xy, pen, *options, start=start, end=end)
  160. def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
  161. """
  162. Draws a polygon.
  163. The polygon outline consists of straight lines between the given
  164. coordinates, plus a straight line between the last and the first
  165. coordinate.
  166. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
  167. """
  168. self.render("polygon", xy, pen, *options)
  169. def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
  170. """
  171. Draws a rectangle.
  172. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
  173. """
  174. self.render("rectangle", xy, pen, *options)
  175. def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None:
  176. """
  177. Draws the string at the given position.
  178. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
  179. """
  180. if self.transform:
  181. path = ImagePath.Path(xy)
  182. path.transform(self.transform)
  183. xy = path
  184. self.draw.text(xy, text, font=font.font, fill=font.color)
  185. def textbbox(
  186. self, xy: tuple[float, float], text: AnyStr, font: Font
  187. ) -> tuple[float, float, float, float]:
  188. """
  189. Returns bounding box (in pixels) of given text.
  190. :return: ``(left, top, right, bottom)`` bounding box
  191. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
  192. """
  193. if self.transform:
  194. path = ImagePath.Path(xy)
  195. path.transform(self.transform)
  196. xy = path
  197. return self.draw.textbbox(xy, text, font=font.font)
  198. def textlength(self, text: AnyStr, font: Font) -> float:
  199. """
  200. Returns length (in pixels) of given text.
  201. This is the amount by which following text should be offset.
  202. .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
  203. """
  204. return self.draw.textlength(text, font=font.font)