ImageDraw.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # drawing interface operations
  6. #
  7. # History:
  8. # 1996-04-13 fl Created (experimental)
  9. # 1996-08-07 fl Filled polygons, ellipses.
  10. # 1996-08-13 fl Added text support
  11. # 1998-06-28 fl Handle I and F images
  12. # 1998-12-29 fl Added arc; use arc primitive to draw ellipses
  13. # 1999-01-10 fl Added shape stuff (experimental)
  14. # 1999-02-06 fl Added bitmap support
  15. # 1999-02-11 fl Changed all primitives to take options
  16. # 1999-02-20 fl Fixed backwards compatibility
  17. # 2000-10-12 fl Copy on write, when necessary
  18. # 2001-02-18 fl Use default ink for bitmap/text also in fill mode
  19. # 2002-10-24 fl Added support for CSS-style color strings
  20. # 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
  21. # 2002-12-11 fl Refactored low-level drawing API (work in progress)
  22. # 2004-08-26 fl Made Draw() a factory function, added getdraw() support
  23. # 2004-09-04 fl Added width support to line primitive
  24. # 2004-09-10 fl Added font mode handling
  25. # 2006-06-19 fl Added font bearing support (getmask2)
  26. #
  27. # Copyright (c) 1997-2006 by Secret Labs AB
  28. # Copyright (c) 1996-2006 by Fredrik Lundh
  29. #
  30. # See the README file for information on usage and redistribution.
  31. #
  32. from __future__ import annotations
  33. __lazy_modules__ = {"math", "struct"}
  34. import math
  35. import struct
  36. from typing import cast
  37. from . import Image, ImageColor, ImageFont, ImageText
  38. TYPE_CHECKING = False
  39. if TYPE_CHECKING:
  40. from collections.abc import Callable, Sequence
  41. from types import ModuleType
  42. from typing import Any, AnyStr
  43. from . import ImageDraw2
  44. from ._typing import Coords, _Ink
  45. # experimental access to the outline API
  46. Outline: Callable[[], Image.core._Outline] = Image.core.outline
  47. """
  48. A simple 2D drawing interface for PIL images.
  49. <p>
  50. Application code should use the <b>Draw</b> factory, instead of
  51. directly.
  52. """
  53. class ImageDraw:
  54. font: ImageFont.BaseImageFont | None = None
  55. def __init__(self, im: Image.Image, mode: str | None = None) -> None:
  56. """
  57. Create a drawing instance.
  58. :param im: The image to draw in.
  59. :param mode: Optional mode to use for color values. For RGB
  60. images, this argument can be RGB or RGBA (to blend the
  61. drawing into the image). For all other modes, this argument
  62. must be the same as the image mode. If omitted, the mode
  63. defaults to the mode of the image.
  64. """
  65. im._ensure_mutable()
  66. blend = 0
  67. if mode is None:
  68. mode = im.mode
  69. if mode != im.mode:
  70. if mode == "RGBA" and im.mode == "RGB":
  71. blend = 1
  72. else:
  73. msg = "mode mismatch"
  74. raise ValueError(msg)
  75. if mode == "P":
  76. self.palette = im.palette
  77. else:
  78. self.palette = None
  79. self._image = im
  80. self.im = im.im
  81. self.draw = Image.core.draw(self.im, blend)
  82. self.mode = mode
  83. if mode in ("I", "F"):
  84. self.ink = self.draw.draw_ink(1)
  85. else:
  86. self.ink = self.draw.draw_ink(-1)
  87. if mode in ("1", "P", "I", "F"):
  88. # FIXME: fix Fill2 to properly support matte for I+F images
  89. self.fontmode = "1"
  90. else:
  91. self.fontmode = "L" # aliasing is okay for other modes
  92. self.fill = False
  93. def getfont(
  94. self,
  95. ) -> ImageFont.BaseImageFont:
  96. """
  97. Get the current default font.
  98. To set the default font for this ImageDraw instance::
  99. from PIL import ImageDraw, ImageFont
  100. draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
  101. To set the default font for all future ImageDraw instances::
  102. from PIL import ImageDraw, ImageFont
  103. ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
  104. If the current default font is ``None``,
  105. it is initialized with ``ImageFont.load_default()``.
  106. :returns: An image font."""
  107. if not self.font:
  108. # FIXME: should add a font repository
  109. self.font = ImageFont.load_default()
  110. return self.font
  111. def _getfont(self, font_size: float | None) -> ImageFont.BaseImageFont:
  112. if font_size is not None:
  113. return ImageFont.load_default(font_size)
  114. else:
  115. return self.getfont()
  116. def _getink(
  117. self, ink: _Ink | None, fill: _Ink | None = None
  118. ) -> tuple[int | None, int | None]:
  119. result_ink = None
  120. result_fill = None
  121. if ink is None and fill is None:
  122. if self.fill:
  123. result_fill = self.ink
  124. else:
  125. result_ink = self.ink
  126. else:
  127. if ink is not None:
  128. if isinstance(ink, str):
  129. ink = ImageColor.getcolor(ink, self.mode)
  130. if self.palette and isinstance(ink, tuple):
  131. ink = self.palette.getcolor(ink, self._image)
  132. result_ink = self.draw.draw_ink(ink)
  133. if fill is not None:
  134. if isinstance(fill, str):
  135. fill = ImageColor.getcolor(fill, self.mode)
  136. if self.palette and isinstance(fill, tuple):
  137. fill = self.palette.getcolor(fill, self._image)
  138. result_fill = self.draw.draw_ink(fill)
  139. return result_ink, result_fill
  140. def arc(
  141. self,
  142. xy: Coords,
  143. start: float,
  144. end: float,
  145. fill: _Ink | None = None,
  146. width: int = 1,
  147. ) -> None:
  148. """Draw an arc."""
  149. ink, fill = self._getink(fill)
  150. if ink is not None and width != 0:
  151. self.draw.draw_arc(xy, start, end, ink, width)
  152. def bitmap(
  153. self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
  154. ) -> None:
  155. """Draw a bitmap."""
  156. bitmap.load()
  157. ink, fill = self._getink(fill)
  158. if ink is None:
  159. ink = fill
  160. if ink is not None:
  161. self.draw.draw_bitmap(xy, bitmap.im, ink)
  162. def chord(
  163. self,
  164. xy: Coords,
  165. start: float,
  166. end: float,
  167. fill: _Ink | None = None,
  168. outline: _Ink | None = None,
  169. width: int = 1,
  170. ) -> None:
  171. """Draw a chord."""
  172. ink, fill_ink = self._getink(outline, fill)
  173. if fill_ink is not None:
  174. self.draw.draw_chord(xy, start, end, fill_ink, 1)
  175. if ink is not None and ink != fill_ink and width != 0:
  176. self.draw.draw_chord(xy, start, end, ink, 0, width)
  177. def ellipse(
  178. self,
  179. xy: Coords,
  180. fill: _Ink | None = None,
  181. outline: _Ink | None = None,
  182. width: int = 1,
  183. ) -> None:
  184. """Draw an ellipse."""
  185. ink, fill_ink = self._getink(outline, fill)
  186. if fill_ink is not None:
  187. self.draw.draw_ellipse(xy, fill_ink, 1)
  188. if ink is not None and ink != fill_ink and width != 0:
  189. self.draw.draw_ellipse(xy, ink, 0, width)
  190. def circle(
  191. self,
  192. xy: Sequence[float],
  193. radius: float,
  194. fill: _Ink | None = None,
  195. outline: _Ink | None = None,
  196. width: int = 1,
  197. ) -> None:
  198. """Draw a circle given center coordinates and a radius."""
  199. ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
  200. self.ellipse(ellipse_xy, fill, outline, width)
  201. def _normalize_coords(self, xy: Coords) -> Sequence[Sequence[float]]:
  202. """Normalize 1 or 2 dimensional coord sequence into 2d sequence."""
  203. if isinstance(xy[0], (list, tuple)):
  204. return cast("Sequence[Sequence[float]]", xy)
  205. else:
  206. return [
  207. cast("Sequence[float]", tuple(xy[i : i + 2]))
  208. for i in range(0, len(xy), 2)
  209. ]
  210. def line(
  211. self,
  212. xy: Coords,
  213. fill: _Ink | None = None,
  214. width: int = 1,
  215. joint: str | None = None,
  216. ) -> None:
  217. """Draw a line, or a connected sequence of line segments."""
  218. ink = self._getink(fill)[0]
  219. if ink is not None and width != 0:
  220. self.draw.draw_lines(xy, ink, width)
  221. if joint == "curve" and width > 4:
  222. points = self._normalize_coords(xy)
  223. for i in range(1, len(points) - 1):
  224. point = points[i]
  225. angles = [
  226. math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
  227. % 360
  228. for start, end in (
  229. (points[i - 1], point),
  230. (point, points[i + 1]),
  231. )
  232. ]
  233. if angles[0] == angles[1]:
  234. # This is a straight line, so no joint is required
  235. continue
  236. def coord_at_angle(
  237. coord: Sequence[float], angle: float
  238. ) -> tuple[float, ...]:
  239. x, y = coord
  240. angle -= 90
  241. distance = width / 2 - 1
  242. return tuple(
  243. p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
  244. for p, p_d in (
  245. (x, distance * math.cos(math.radians(angle))),
  246. (y, distance * math.sin(math.radians(angle))),
  247. )
  248. )
  249. flipped = (
  250. angles[1] > angles[0] and angles[1] - 180 > angles[0]
  251. ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
  252. coords = [
  253. (point[0] - width / 2 + 1, point[1] - width / 2 + 1),
  254. (point[0] + width / 2 - 1, point[1] + width / 2 - 1),
  255. ]
  256. if flipped:
  257. start, end = (angles[1] + 90, angles[0] + 90)
  258. else:
  259. start, end = (angles[0] - 90, angles[1] - 90)
  260. self.pieslice(coords, start - 90, end - 90, fill)
  261. if width > 8:
  262. # Cover potential gaps between the line and the joint
  263. if flipped:
  264. gap_coords = [
  265. coord_at_angle(point, angles[0] + 90),
  266. point,
  267. coord_at_angle(point, angles[1] + 90),
  268. ]
  269. else:
  270. gap_coords = [
  271. coord_at_angle(point, angles[0] - 90),
  272. point,
  273. coord_at_angle(point, angles[1] - 90),
  274. ]
  275. self.line(gap_coords, fill, width=3)
  276. def shape(
  277. self,
  278. shape: Image.core._Outline,
  279. fill: _Ink | None = None,
  280. outline: _Ink | None = None,
  281. ) -> None:
  282. """(Experimental) Draw a shape."""
  283. shape.close()
  284. ink, fill_ink = self._getink(outline, fill)
  285. if fill_ink is not None:
  286. self.draw.draw_outline(shape, fill_ink, 1)
  287. if ink is not None and ink != fill_ink:
  288. self.draw.draw_outline(shape, ink, 0)
  289. def pieslice(
  290. self,
  291. xy: Coords,
  292. start: float,
  293. end: float,
  294. fill: _Ink | None = None,
  295. outline: _Ink | None = None,
  296. width: int = 1,
  297. ) -> None:
  298. """Draw a pieslice."""
  299. ink, fill_ink = self._getink(outline, fill)
  300. if fill_ink is not None:
  301. self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
  302. if ink is not None and ink != fill_ink and width != 0:
  303. self.draw.draw_pieslice(xy, start, end, ink, 0, width)
  304. def point(self, xy: Coords, fill: _Ink | None = None) -> None:
  305. """Draw one or more individual pixels."""
  306. ink, fill = self._getink(fill)
  307. if ink is not None:
  308. self.draw.draw_points(xy, ink)
  309. def polygon(
  310. self,
  311. xy: Coords,
  312. fill: _Ink | None = None,
  313. outline: _Ink | None = None,
  314. width: int = 1,
  315. ) -> None:
  316. """Draw a polygon."""
  317. ink, fill_ink = self._getink(outline, fill)
  318. if fill_ink is not None:
  319. self.draw.draw_polygon(xy, fill_ink, 1)
  320. if ink is not None and ink != fill_ink and width != 0:
  321. if width == 1:
  322. self.draw.draw_polygon(xy, ink, 0, width)
  323. elif self.im is not None:
  324. # To avoid expanding the polygon outwards,
  325. # use the fill as a mask
  326. mask = Image.new("1", self.im.size)
  327. mask_ink = self._getink(1)[0]
  328. draw = Draw(mask)
  329. draw.draw.draw_polygon(xy, mask_ink, 1)
  330. self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im)
  331. def regular_polygon(
  332. self,
  333. bounding_circle: Sequence[Sequence[float] | float],
  334. n_sides: int,
  335. rotation: float = 0,
  336. fill: _Ink | None = None,
  337. outline: _Ink | None = None,
  338. width: int = 1,
  339. ) -> None:
  340. """Draw a regular polygon."""
  341. xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
  342. self.polygon(xy, fill, outline, width)
  343. def rectangle(
  344. self,
  345. xy: Coords,
  346. fill: _Ink | None = None,
  347. outline: _Ink | None = None,
  348. width: int = 1,
  349. ) -> None:
  350. """Draw a rectangle."""
  351. ink, fill_ink = self._getink(outline, fill)
  352. if fill_ink is not None:
  353. self.draw.draw_rectangle(xy, fill_ink, 1)
  354. if ink is not None and ink != fill_ink and width != 0:
  355. self.draw.draw_rectangle(xy, ink, 0, width)
  356. def rounded_rectangle(
  357. self,
  358. xy: Coords,
  359. radius: float = 0,
  360. fill: _Ink | None = None,
  361. outline: _Ink | None = None,
  362. width: int = 1,
  363. *,
  364. corners: tuple[bool, bool, bool, bool] | None = None,
  365. ) -> None:
  366. """Draw a rounded rectangle."""
  367. (x0, y0), (x1, y1) = self._normalize_coords(xy)
  368. if x1 < x0:
  369. msg = "x1 must be greater than or equal to x0"
  370. raise ValueError(msg)
  371. if y1 < y0:
  372. msg = "y1 must be greater than or equal to y0"
  373. raise ValueError(msg)
  374. if corners is None:
  375. corners = (True, True, True, True)
  376. d = min(x1 - x0, y1 - y0, radius * 2)
  377. x0 = round(x0)
  378. y0 = round(y0)
  379. x1 = round(x1)
  380. y1 = round(y1)
  381. full_x, full_y = False, False
  382. if all(corners):
  383. full_x = d >= x1 - x0 - 1
  384. if full_x:
  385. # The two left and two right corners are joined
  386. d = x1 - x0
  387. full_y = d >= y1 - y0 - 1
  388. if full_y:
  389. # The two top and two bottom corners are joined
  390. d = y1 - y0
  391. if full_x and full_y:
  392. # If all corners are joined, that is a circle
  393. return self.ellipse(xy, fill, outline, width)
  394. if d == 0 or not any(corners):
  395. # If the corners have no curve,
  396. # or there are no corners,
  397. # that is a rectangle
  398. return self.rectangle(xy, fill, outline, width)
  399. r = int(d // 2)
  400. ink, fill_ink = self._getink(outline, fill)
  401. def draw_corners(pieslice: bool) -> None:
  402. parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
  403. if full_x:
  404. # Draw top and bottom halves
  405. parts = (
  406. ((x0, y0, x0 + d, y0 + d), 180, 360),
  407. ((x0, y1 - d, x0 + d, y1), 0, 180),
  408. )
  409. elif full_y:
  410. # Draw left and right halves
  411. parts = (
  412. ((x0, y0, x0 + d, y0 + d), 90, 270),
  413. ((x1 - d, y0, x1, y0 + d), 270, 90),
  414. )
  415. else:
  416. # Draw four separate corners
  417. parts = tuple(
  418. part
  419. for i, part in enumerate(
  420. (
  421. ((x0, y0, x0 + d, y0 + d), 180, 270),
  422. ((x1 - d, y0, x1, y0 + d), 270, 360),
  423. ((x1 - d, y1 - d, x1, y1), 0, 90),
  424. ((x0, y1 - d, x0 + d, y1), 90, 180),
  425. )
  426. )
  427. if corners[i]
  428. )
  429. for part in parts:
  430. if pieslice:
  431. self.draw.draw_pieslice(*(part + (fill_ink, 1)))
  432. else:
  433. self.draw.draw_arc(*(part + (ink, width)))
  434. if fill_ink is not None:
  435. draw_corners(True)
  436. if full_x:
  437. self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
  438. elif x1 - r - 1 >= x0 + r + 1:
  439. self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
  440. if not full_x and not full_y:
  441. left = [x0, y0, x0 + r, y1]
  442. if corners[0]:
  443. left[1] += r + 1
  444. if corners[3]:
  445. left[3] -= r + 1
  446. self.draw.draw_rectangle(left, fill_ink, 1)
  447. right = [x1 - r, y0, x1, y1]
  448. if corners[1]:
  449. right[1] += r + 1
  450. if corners[2]:
  451. right[3] -= r + 1
  452. self.draw.draw_rectangle(right, fill_ink, 1)
  453. if ink is not None and ink != fill_ink and width != 0:
  454. draw_corners(False)
  455. if not full_x:
  456. top = [x0, y0, x1, y0 + width - 1]
  457. if corners[0]:
  458. top[0] += r + 1
  459. if corners[1]:
  460. top[2] -= r + 1
  461. self.draw.draw_rectangle(top, ink, 1)
  462. bottom = [x0, y1 - width + 1, x1, y1]
  463. if corners[3]:
  464. bottom[0] += r + 1
  465. if corners[2]:
  466. bottom[2] -= r + 1
  467. self.draw.draw_rectangle(bottom, ink, 1)
  468. if not full_y:
  469. left = [x0, y0, x0 + width - 1, y1]
  470. if corners[0]:
  471. left[1] += r + 1
  472. if corners[3]:
  473. left[3] -= r + 1
  474. self.draw.draw_rectangle(left, ink, 1)
  475. right = [x1 - width + 1, y0, x1, y1]
  476. if corners[1]:
  477. right[1] += r + 1
  478. if corners[2]:
  479. right[3] -= r + 1
  480. self.draw.draw_rectangle(right, ink, 1)
  481. def text(
  482. self,
  483. xy: tuple[float, float],
  484. text: AnyStr | ImageText.Text[AnyStr],
  485. fill: _Ink | None = None,
  486. font: ImageFont.BaseImageFont | None = None,
  487. anchor: str | None = None,
  488. spacing: float = 4,
  489. align: str = "left",
  490. direction: str | None = None,
  491. features: list[str] | None = None,
  492. language: str | None = None,
  493. stroke_width: float = 0,
  494. stroke_fill: _Ink | None = None,
  495. embedded_color: bool = False,
  496. *args: Any,
  497. **kwargs: Any,
  498. ) -> None:
  499. """Draw text."""
  500. if isinstance(text, ImageText.Text):
  501. image_text = text
  502. else:
  503. if font is None:
  504. font = self._getfont(kwargs.get("font_size"))
  505. image_text = ImageText.Text(
  506. text, font, self.mode, spacing, direction, features, language
  507. )
  508. if embedded_color:
  509. image_text.embed_color()
  510. if stroke_width:
  511. image_text.stroke(stroke_width, stroke_fill)
  512. def getink(fill: _Ink | None) -> int:
  513. ink, fill_ink = self._getink(fill)
  514. if ink is None:
  515. assert fill_ink is not None
  516. return fill_ink
  517. return ink
  518. ink = getink(fill)
  519. if ink is None:
  520. return
  521. stroke_ink = None
  522. if image_text.stroke_width:
  523. stroke_ink = (
  524. getink(image_text.stroke_fill)
  525. if image_text.stroke_fill is not None
  526. else ink
  527. )
  528. for line in image_text._split(xy, anchor, align):
  529. def draw_text(ink: int, stroke_width: float = 0) -> None:
  530. mode = self.fontmode
  531. if stroke_width == 0 and embedded_color:
  532. mode = "RGBA"
  533. x = int(line.x)
  534. y = int(line.y)
  535. start = (math.modf(line.x)[0], math.modf(line.y)[0])
  536. if isinstance(image_text.font, ImageFont.FreeTypeFont):
  537. mask, offset = image_text.font.getmask2(
  538. line.text,
  539. mode,
  540. direction,
  541. features,
  542. language,
  543. stroke_width,
  544. line.anchor,
  545. ink,
  546. start,
  547. stroke_filled=True,
  548. *args,
  549. **kwargs,
  550. )
  551. x += offset[0]
  552. y += offset[1]
  553. else:
  554. try:
  555. mask = image_text.font.getmask(
  556. line.text,
  557. mode,
  558. direction,
  559. features,
  560. language,
  561. stroke_width,
  562. line.anchor,
  563. ink,
  564. start=start,
  565. *args,
  566. **kwargs,
  567. )
  568. except TypeError:
  569. mask = image_text.font.getmask(line.text)
  570. if mode == "RGBA":
  571. # image_text.font.getmask2(mode="RGBA")
  572. # returns color in RGB bands and mask in A
  573. # extract mask and set text alpha
  574. color, mask = mask, mask.getband(3)
  575. ink_alpha = struct.pack("i", ink)[3]
  576. color.fillband(3, ink_alpha)
  577. if self.im is not None:
  578. self.im.paste(
  579. color, (x, y, x + mask.size[0], y + mask.size[1]), mask
  580. )
  581. else:
  582. self.draw.draw_bitmap((x, y), mask, ink)
  583. if stroke_ink is not None:
  584. # Draw stroked text
  585. draw_text(stroke_ink, image_text.stroke_width)
  586. # Draw normal text
  587. if ink != stroke_ink:
  588. draw_text(ink)
  589. else:
  590. # Only draw normal text
  591. draw_text(ink)
  592. def multiline_text(
  593. self,
  594. xy: tuple[float, float],
  595. text: AnyStr,
  596. fill: _Ink | None = None,
  597. font: ImageFont.BaseImageFont | None = None,
  598. anchor: str | None = None,
  599. spacing: float = 4,
  600. align: str = "left",
  601. direction: str | None = None,
  602. features: list[str] | None = None,
  603. language: str | None = None,
  604. stroke_width: float = 0,
  605. stroke_fill: _Ink | None = None,
  606. embedded_color: bool = False,
  607. *,
  608. font_size: float | None = None,
  609. ) -> None:
  610. return self.text(
  611. xy,
  612. text,
  613. fill,
  614. font,
  615. anchor,
  616. spacing,
  617. align,
  618. direction,
  619. features,
  620. language,
  621. stroke_width,
  622. stroke_fill,
  623. embedded_color,
  624. font_size=font_size,
  625. )
  626. def textlength(
  627. self,
  628. text: AnyStr,
  629. font: ImageFont.BaseImageFont | None = None,
  630. direction: str | None = None,
  631. features: list[str] | None = None,
  632. language: str | None = None,
  633. embedded_color: bool = False,
  634. *,
  635. font_size: float | None = None,
  636. ) -> float:
  637. """Get the length of a given string, in pixels with 1/64 precision."""
  638. if font is None:
  639. font = self._getfont(font_size)
  640. image_text = ImageText.Text(
  641. text,
  642. font,
  643. self.mode,
  644. direction=direction,
  645. features=features,
  646. language=language,
  647. )
  648. if embedded_color:
  649. image_text.embed_color()
  650. return image_text.get_length()
  651. def textbbox(
  652. self,
  653. xy: tuple[float, float],
  654. text: AnyStr,
  655. font: ImageFont.BaseImageFont | None = None,
  656. anchor: str | None = None,
  657. spacing: float = 4,
  658. align: str = "left",
  659. direction: str | None = None,
  660. features: list[str] | None = None,
  661. language: str | None = None,
  662. stroke_width: float = 0,
  663. embedded_color: bool = False,
  664. *,
  665. font_size: float | None = None,
  666. ) -> tuple[float, float, float, float]:
  667. """Get the bounding box of a given string, in pixels."""
  668. if font is None:
  669. font = self._getfont(font_size)
  670. image_text = ImageText.Text(
  671. text, font, self.mode, spacing, direction, features, language
  672. )
  673. if embedded_color:
  674. image_text.embed_color()
  675. if stroke_width:
  676. image_text.stroke(stroke_width)
  677. return image_text.get_bbox(xy, anchor, align)
  678. def multiline_textbbox(
  679. self,
  680. xy: tuple[float, float],
  681. text: AnyStr,
  682. font: ImageFont.BaseImageFont | None = None,
  683. anchor: str | None = None,
  684. spacing: float = 4,
  685. align: str = "left",
  686. direction: str | None = None,
  687. features: list[str] | None = None,
  688. language: str | None = None,
  689. stroke_width: float = 0,
  690. embedded_color: bool = False,
  691. *,
  692. font_size: float | None = None,
  693. ) -> tuple[float, float, float, float]:
  694. return self.textbbox(
  695. xy,
  696. text,
  697. font,
  698. anchor,
  699. spacing,
  700. align,
  701. direction,
  702. features,
  703. language,
  704. stroke_width,
  705. embedded_color,
  706. font_size=font_size,
  707. )
  708. def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
  709. """
  710. A simple 2D drawing interface for PIL images.
  711. :param im: The image to draw in.
  712. :param mode: Optional mode to use for color values. For RGB
  713. images, this argument can be RGB or RGBA (to blend the
  714. drawing into the image). For all other modes, this argument
  715. must be the same as the image mode. If omitted, the mode
  716. defaults to the mode of the image.
  717. """
  718. try:
  719. return getattr(im, "getdraw")(mode)
  720. except AttributeError:
  721. return ImageDraw(im, mode)
  722. def getdraw(im: Image.Image | None = None) -> tuple[ImageDraw2.Draw | None, ModuleType]:
  723. """
  724. :param im: The image to draw in.
  725. :returns: A (drawing context, drawing resource factory) tuple.
  726. """
  727. from . import ImageDraw2
  728. draw = ImageDraw2.Draw(im) if im is not None else None
  729. return draw, ImageDraw2
  730. def floodfill(
  731. image: Image.Image,
  732. xy: tuple[int, int],
  733. value: float | tuple[int, ...],
  734. border: float | tuple[int, ...] | None = None,
  735. thresh: float = 0,
  736. ) -> None:
  737. """
  738. .. warning:: This method is experimental.
  739. Fills a bounded region with a given color.
  740. :param image: Target image.
  741. :param xy: Seed position (a 2-item coordinate tuple). See
  742. :ref:`coordinate-system`.
  743. :param value: Fill color.
  744. :param border: Optional border value. If given, the region consists of
  745. pixels with a color different from the border color. If not given,
  746. the region consists of pixels having the same color as the seed
  747. pixel.
  748. :param thresh: Optional threshold value which specifies a maximum
  749. tolerable difference of a pixel value from the 'background' in
  750. order for it to be replaced. Useful for filling regions of
  751. non-homogeneous, but similar, colors.
  752. """
  753. # based on an implementation by Eric S. Raymond
  754. # amended by yo1995 @20180806
  755. pixel = image.load()
  756. assert pixel is not None
  757. x, y = xy
  758. try:
  759. background = pixel[x, y]
  760. if _color_diff(value, background) <= thresh:
  761. return # seed point already has fill color
  762. pixel[x, y] = value
  763. except (ValueError, IndexError):
  764. return # seed point outside image
  765. edge = {(x, y)}
  766. # use a set to keep record of current and previous edge pixels
  767. # to reduce memory consumption
  768. full_edge = set()
  769. while edge:
  770. new_edge = set()
  771. for x, y in edge: # 4 adjacent method
  772. for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
  773. # If already processed, or if a coordinate is negative, skip
  774. if (s, t) in full_edge or s < 0 or t < 0:
  775. continue
  776. try:
  777. p = pixel[s, t]
  778. except (ValueError, IndexError):
  779. pass
  780. else:
  781. full_edge.add((s, t))
  782. if border is None:
  783. fill = _color_diff(p, background) <= thresh
  784. else:
  785. fill = p not in (value, border)
  786. if fill:
  787. pixel[s, t] = value
  788. new_edge.add((s, t))
  789. full_edge = edge # discard pixels processed
  790. edge = new_edge
  791. def _compute_regular_polygon_vertices(
  792. bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
  793. ) -> list[tuple[float, float]]:
  794. """
  795. Generate a list of vertices for a 2D regular polygon.
  796. :param bounding_circle: The bounding circle is a sequence defined
  797. by a point and radius. The polygon is inscribed in this circle.
  798. (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
  799. :param n_sides: Number of sides
  800. (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
  801. :param rotation: Apply an arbitrary rotation to the polygon
  802. (e.g. ``rotation=90``, applies a 90 degree rotation)
  803. :return: List of regular polygon vertices
  804. (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
  805. How are the vertices computed?
  806. 1. Compute the following variables
  807. - theta: Angle between the apothem & the nearest polygon vertex
  808. - side_length: Length of each polygon edge
  809. - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
  810. - polygon_radius: Polygon radius (last element of bounding_circle)
  811. - angles: Location of each polygon vertex in polar grid
  812. (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
  813. 2. For each angle in angles, get the polygon vertex at that angle
  814. The vertex is computed using the equation below.
  815. X= xcos(φ) + ysin(φ)
  816. Y= −xsin(φ) + ycos(φ)
  817. Note:
  818. φ = angle in degrees
  819. x = 0
  820. y = polygon_radius
  821. The formula above assumes rotation around the origin.
  822. In our case, we are rotating around the centroid.
  823. To account for this, we use the formula below
  824. X = xcos(φ) + ysin(φ) + centroid_x
  825. Y = −xsin(φ) + ycos(φ) + centroid_y
  826. """
  827. # 1. Error Handling
  828. # 1.1 Check `n_sides` has an appropriate value
  829. if not isinstance(n_sides, int):
  830. msg = "n_sides should be an int" # type: ignore[unreachable]
  831. raise TypeError(msg)
  832. if n_sides < 3:
  833. msg = "n_sides should be an int > 2"
  834. raise ValueError(msg)
  835. # 1.2 Check `bounding_circle` has an appropriate value
  836. if not isinstance(bounding_circle, (list, tuple)):
  837. msg = "bounding_circle should be a sequence"
  838. raise TypeError(msg)
  839. if len(bounding_circle) == 3:
  840. if not all(isinstance(i, (int, float)) for i in bounding_circle):
  841. msg = "bounding_circle should only contain numeric data"
  842. raise ValueError(msg)
  843. *centroid, polygon_radius = cast("list[float]", list(bounding_circle))
  844. elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
  845. if not all(
  846. isinstance(i, (int, float)) for i in bounding_circle[0]
  847. ) or not isinstance(bounding_circle[1], (int, float)):
  848. msg = "bounding_circle should only contain numeric data"
  849. raise ValueError(msg)
  850. if len(bounding_circle[0]) != 2:
  851. msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
  852. raise ValueError(msg)
  853. centroid = cast("list[float]", list(bounding_circle[0]))
  854. polygon_radius = cast("float", bounding_circle[1])
  855. else:
  856. msg = (
  857. "bounding_circle should contain 2D coordinates "
  858. "and a radius (e.g. (x, y, r) or ((x, y), r) )"
  859. )
  860. raise ValueError(msg)
  861. if polygon_radius <= 0:
  862. msg = "bounding_circle radius should be > 0"
  863. raise ValueError(msg)
  864. # 1.3 Check `rotation` has an appropriate value
  865. if not isinstance(rotation, (int, float)):
  866. msg = "rotation should be an int or float" # type: ignore[unreachable]
  867. raise ValueError(msg)
  868. # 2. Define Helper Functions
  869. def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
  870. return (
  871. round(
  872. point[0] * math.cos(math.radians(360 - degrees))
  873. - point[1] * math.sin(math.radians(360 - degrees))
  874. + centroid[0],
  875. 2,
  876. ),
  877. round(
  878. point[1] * math.cos(math.radians(360 - degrees))
  879. + point[0] * math.sin(math.radians(360 - degrees))
  880. + centroid[1],
  881. 2,
  882. ),
  883. )
  884. def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
  885. start_point = [polygon_radius, 0]
  886. return _apply_rotation(start_point, angle)
  887. def _get_angles(n_sides: int, rotation: float) -> list[float]:
  888. angles = []
  889. degrees = 360 / n_sides
  890. # Start with the bottom left polygon vertex
  891. current_angle = (270 - 0.5 * degrees) + rotation
  892. for _ in range(n_sides):
  893. angles.append(current_angle)
  894. current_angle += degrees
  895. if current_angle > 360:
  896. current_angle -= 360
  897. return angles
  898. # 3. Variable Declarations
  899. angles = _get_angles(n_sides, rotation)
  900. # 4. Compute Vertices
  901. return [_compute_polygon_vertex(angle) for angle in angles]
  902. def _color_diff(
  903. color1: float | tuple[int, ...], color2: float | tuple[int, ...]
  904. ) -> float:
  905. """
  906. Uses 1-norm distance to calculate difference between two values.
  907. """
  908. first = color1 if isinstance(color1, tuple) else (color1,)
  909. second = color2 if isinstance(color2, tuple) else (color2,)
  910. return sum(abs(first[i] - second[i]) for i in range(len(second)))