ImageDraw.py 35 KB

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