Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageDraw.py 38KB

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