ImageText.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. from __future__ import annotations
  2. __lazy_modules__ = {"math", "re"}
  3. import math
  4. import re
  5. from typing import AnyStr, Generic, NamedTuple
  6. from . import ImageFont
  7. TYPE_CHECKING = False
  8. if TYPE_CHECKING:
  9. from ._typing import _Ink
  10. class _Line(NamedTuple):
  11. x: float
  12. y: float
  13. anchor: str
  14. text: str | bytes
  15. class _Wrap(Generic[AnyStr]):
  16. lines: list[AnyStr] = []
  17. position = 0
  18. offset = 0
  19. def __init__(
  20. self,
  21. text: Text[AnyStr],
  22. width: int,
  23. height: int | None = None,
  24. font: ImageFont.BaseImageFont | None = None,
  25. ) -> None:
  26. self.text: Text[AnyStr] = text
  27. self.width = width
  28. self.height = height
  29. self.font = font
  30. input_text = self.text.text
  31. emptystring = "" if isinstance(input_text, str) else b""
  32. line = emptystring
  33. for word in re.findall(
  34. r"\s*\S+" if isinstance(input_text, str) else rb"\s*\S+", input_text
  35. ):
  36. newlines = re.findall(
  37. r"[^\S\n]*\n" if isinstance(input_text, str) else rb"[^\S\n]*\n", word
  38. )
  39. if newlines:
  40. if not self.add_line(line):
  41. break
  42. for i, line in enumerate(newlines):
  43. if i != 0 and not self.add_line(emptystring):
  44. break
  45. self.position += len(line)
  46. word = word[len(line) :]
  47. line = emptystring
  48. new_line = line + word
  49. if self.text._get_bbox(new_line, self.font)[2] <= width:
  50. # This word fits on the line
  51. line = new_line
  52. continue
  53. # This word does not fit on the line
  54. if line and not self.add_line(line):
  55. break
  56. original_length = len(word)
  57. word = word.lstrip()
  58. self.offset = original_length - len(word)
  59. if self.text._get_bbox(word, self.font)[2] > width:
  60. if font is None:
  61. msg = "Word does not fit within line"
  62. raise ValueError(msg)
  63. break
  64. line = word
  65. else:
  66. if line:
  67. self.add_line(line)
  68. self.remaining_text: AnyStr = input_text[self.position :]
  69. def add_line(self, line: AnyStr) -> bool:
  70. lines = self.lines + [line]
  71. if self.height is not None:
  72. last_line_y = self.text._split(lines=lines)[-1].y
  73. last_line_height = self.text._get_bbox(line, self.font)[3]
  74. if last_line_y + last_line_height > self.height:
  75. return False
  76. self.lines = lines
  77. self.position += len(line) + self.offset
  78. self.offset = 0
  79. return True
  80. class Text(Generic[AnyStr]):
  81. def __init__(
  82. self,
  83. text: AnyStr,
  84. font: ImageFont.BaseImageFont | None = None,
  85. mode: str = "RGB",
  86. spacing: float = 4,
  87. direction: str | None = None,
  88. features: list[str] | None = None,
  89. language: str | None = None,
  90. ) -> None:
  91. """
  92. :param text: String to be drawn.
  93. :param font: Either an :py:class:`~PIL.ImageFont.ImageFont` instance,
  94. :py:class:`~PIL.ImageFont.FreeTypeFont` instance,
  95. :py:class:`~PIL.ImageFont.TransposedFont` instance or ``None``. If
  96. ``None``, the default font from :py:meth:`.ImageFont.load_default`
  97. will be used.
  98. :param mode: The image mode this will be used with.
  99. :param spacing: The number of pixels between lines.
  100. :param direction: Direction of the text. It can be ``"rtl"`` (right to left),
  101. ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
  102. Requires libraqm.
  103. :param features: A list of OpenType font features to be used during text
  104. layout. This is usually used to turn on optional font features
  105. that are not enabled by default, for example ``"dlig"`` or
  106. ``"ss01"``, but can be also used to turn off default font
  107. features, for example ``"-liga"`` to disable ligatures or
  108. ``"-kern"`` to disable kerning. To get all supported
  109. features, see `OpenType docs`_.
  110. Requires libraqm.
  111. :param language: Language of the text. Different languages may use
  112. different glyph shapes or ligatures. This parameter tells
  113. the font which language the text is in, and to apply the
  114. correct substitutions as appropriate, if available.
  115. It should be a `BCP 47 language code`_.
  116. Requires libraqm.
  117. """
  118. self.text: AnyStr = text
  119. self.font = font or ImageFont.load_default()
  120. self.mode = mode
  121. self.spacing = spacing
  122. self.direction = direction
  123. self.features = features
  124. self.language = language
  125. self.embedded_color = False
  126. self.stroke_width: float = 0
  127. self.stroke_fill: _Ink | None = None
  128. def embed_color(self) -> None:
  129. """
  130. Use embedded color glyphs (COLR, CBDT, SBIX).
  131. """
  132. if self.mode not in ("RGB", "RGBA"):
  133. msg = "Embedded color supported only in RGB and RGBA modes"
  134. raise ValueError(msg)
  135. self.embedded_color = True
  136. def stroke(self, width: float = 0, fill: _Ink | None = None) -> None:
  137. """
  138. :param width: The width of the text stroke.
  139. :param fill: Color to use for the text stroke when drawing. If not given, will
  140. default to the ``fill`` parameter from
  141. :py:meth:`.ImageDraw.ImageDraw.text`.
  142. """
  143. self.stroke_width = width
  144. self.stroke_fill = fill
  145. def _get_fontmode(self) -> str:
  146. if self.mode in ("1", "P", "I", "F"):
  147. return "1"
  148. elif self.embedded_color:
  149. return "RGBA"
  150. else:
  151. return "L"
  152. def wrap(
  153. self,
  154. width: int,
  155. height: int | None = None,
  156. scaling: str | tuple[str, int] | None = None,
  157. ) -> Text[AnyStr] | None:
  158. """
  159. Wrap text to fit within a given width.
  160. :param width: The width to fit within.
  161. :param height: An optional height limit. Any text that does not fit within this
  162. will be returned as a new :py:class:`.Text` object.
  163. :param scaling: An optional directive to scale the text, either "grow" as much
  164. as possible within the given dimensions, or "shrink" until it
  165. fits. It can also be a tuple of (direction, limit), with an
  166. integer limit to stop scaling at.
  167. :returns: An :py:class:`.Text` object, or None.
  168. """
  169. if isinstance(self.font, ImageFont.TransposedFont):
  170. msg = "TransposedFont not supported"
  171. raise ValueError(msg)
  172. if self.direction not in (None, "ltr"):
  173. msg = "Only ltr direction supported"
  174. raise ValueError(msg)
  175. if scaling is None:
  176. wrap = _Wrap(self, width, height)
  177. else:
  178. if not isinstance(self.font, ImageFont.FreeTypeFont):
  179. msg = "'scaling' only supports FreeTypeFont"
  180. raise ValueError(msg)
  181. if height is None:
  182. msg = "'scaling' requires 'height'"
  183. raise ValueError(msg)
  184. if isinstance(scaling, str):
  185. limit = 1
  186. else:
  187. scaling, limit = scaling
  188. font = self.font
  189. wrap = _Wrap(self, width, height, font)
  190. if scaling == "shrink":
  191. if wrap.remaining_text:
  192. size = math.ceil(font.size)
  193. while wrap.remaining_text:
  194. if size == max(limit, 1):
  195. msg = "Text could not be scaled"
  196. raise ValueError(msg)
  197. size -= 1
  198. font = self.font.font_variant(size=size)
  199. wrap = _Wrap(self, width, height, font)
  200. self.font = font
  201. else:
  202. if wrap.remaining_text:
  203. msg = "Text could not be scaled"
  204. raise ValueError(msg)
  205. size = math.floor(font.size)
  206. while not wrap.remaining_text:
  207. if size == limit:
  208. msg = "Text could not be scaled"
  209. raise ValueError(msg)
  210. size += 1
  211. font = self.font.font_variant(size=size)
  212. last_wrap = wrap
  213. wrap = _Wrap(self, width, height, font)
  214. size -= 1
  215. if size != self.font.size:
  216. self.font = self.font.font_variant(size=size)
  217. wrap = last_wrap
  218. if wrap.remaining_text:
  219. text = Text(
  220. text=wrap.remaining_text,
  221. font=self.font,
  222. mode=self.mode,
  223. spacing=self.spacing,
  224. direction=self.direction,
  225. features=self.features,
  226. language=self.language,
  227. )
  228. text.embedded_color = self.embedded_color
  229. text.stroke_width = self.stroke_width
  230. text.stroke_fill = self.stroke_fill
  231. else:
  232. text = None
  233. newline = "\n" if isinstance(self.text, str) else b"\n"
  234. self.text = newline.join(wrap.lines)
  235. return text
  236. def get_length(self) -> float:
  237. """
  238. Returns length (in pixels with 1/64 precision) of text.
  239. This is the amount by which following text should be offset.
  240. Text bounding box may extend past the length in some fonts,
  241. e.g. when using italics or accents.
  242. The result is returned as a float; it is a whole number if using basic layout.
  243. Note that the sum of two lengths may not equal the length of a concatenated
  244. string due to kerning. If you need to adjust for kerning, include the following
  245. character and subtract its length.
  246. For example, instead of::
  247. hello = ImageText.Text("Hello", font).get_length()
  248. world = ImageText.Text("World", font).get_length()
  249. helloworld = ImageText.Text("HelloWorld", font).get_length()
  250. assert hello + world == helloworld
  251. use::
  252. hello = (
  253. ImageText.Text("HelloW", font).get_length() -
  254. ImageText.Text("W", font).get_length()
  255. ) # adjusted for kerning
  256. world = ImageText.Text("World", font).get_length()
  257. helloworld = ImageText.Text("HelloWorld", font).get_length()
  258. assert hello + world == helloworld
  259. or disable kerning with (requires libraqm)::
  260. hello = ImageText.Text("Hello", font, features=["-kern"]).get_length()
  261. world = ImageText.Text("World", font, features=["-kern"]).get_length()
  262. helloworld = ImageText.Text(
  263. "HelloWorld", font, features=["-kern"]
  264. ).get_length()
  265. assert hello + world == helloworld
  266. :return: Either width for horizontal text, or height for vertical text.
  267. """
  268. if isinstance(self.text, str):
  269. multiline = "\n" in self.text
  270. else:
  271. multiline = b"\n" in self.text
  272. if multiline:
  273. msg = "can't measure length of multiline text"
  274. raise ValueError(msg)
  275. return self.font.getlength(
  276. self.text,
  277. self._get_fontmode(),
  278. self.direction,
  279. self.features,
  280. self.language,
  281. )
  282. def _split(
  283. self,
  284. xy: tuple[float, float] = (0, 0),
  285. anchor: str | None = None,
  286. align: str = "left",
  287. lines: list[str] | list[bytes] | None = None,
  288. ) -> list[_Line]:
  289. if anchor is None:
  290. anchor = "lt" if self.direction == "ttb" else "la"
  291. elif len(anchor) != 2:
  292. msg = "anchor must be a 2 character string"
  293. raise ValueError(msg)
  294. if lines is None:
  295. lines = (
  296. self.text.split("\n")
  297. if isinstance(self.text, str)
  298. else self.text.split(b"\n")
  299. )
  300. if len(lines) == 1:
  301. return [_Line(xy[0], xy[1], anchor, lines[0])]
  302. if anchor[1] in "tb" and self.direction != "ttb":
  303. msg = "anchor not supported for multiline text"
  304. raise ValueError(msg)
  305. fontmode = self._get_fontmode()
  306. line_spacing = (
  307. self.font.getbbox(
  308. "A",
  309. fontmode,
  310. None,
  311. self.features,
  312. self.language,
  313. self.stroke_width,
  314. )[3]
  315. + self.stroke_width
  316. + self.spacing
  317. )
  318. top = xy[1]
  319. parts = []
  320. if self.direction == "ttb":
  321. left = xy[0]
  322. for line in lines:
  323. parts.append(_Line(left, top, anchor, line))
  324. left += line_spacing
  325. else:
  326. widths = []
  327. max_width: float = 0
  328. for line in lines:
  329. line_width = self.font.getlength(
  330. line, fontmode, self.direction, self.features, self.language
  331. )
  332. widths.append(line_width)
  333. max_width = max(max_width, line_width)
  334. if anchor[1] == "m":
  335. top -= (len(lines) - 1) * line_spacing / 2.0
  336. elif anchor[1] == "d":
  337. top -= (len(lines) - 1) * line_spacing
  338. idx = -1
  339. for line in lines:
  340. left = xy[0]
  341. idx += 1
  342. width_difference = max_width - widths[idx]
  343. # align by align parameter
  344. if align in ("left", "justify"):
  345. pass
  346. elif align == "center":
  347. left += width_difference / 2.0
  348. elif align == "right":
  349. left += width_difference
  350. else:
  351. msg = 'align must be "left", "center", "right" or "justify"'
  352. raise ValueError(msg)
  353. if (
  354. align == "justify"
  355. and width_difference != 0
  356. and idx != len(lines) - 1
  357. ):
  358. words = (
  359. line.split(" ") if isinstance(line, str) else line.split(b" ")
  360. )
  361. if len(words) > 1:
  362. # align left by anchor
  363. if anchor[0] == "m":
  364. left -= max_width / 2.0
  365. elif anchor[0] == "r":
  366. left -= max_width
  367. word_widths = [
  368. self.font.getlength(
  369. word,
  370. fontmode,
  371. self.direction,
  372. self.features,
  373. self.language,
  374. )
  375. for word in words
  376. ]
  377. word_anchor = "l" + anchor[1]
  378. width_difference = max_width - sum(word_widths)
  379. i = 0
  380. for word in words:
  381. parts.append(_Line(left, top, word_anchor, word))
  382. left += word_widths[i] + width_difference / (len(words) - 1)
  383. i += 1
  384. top += line_spacing
  385. continue
  386. # align left by anchor
  387. if anchor[0] == "m":
  388. left -= width_difference / 2.0
  389. elif anchor[0] == "r":
  390. left -= width_difference
  391. parts.append(_Line(left, top, anchor, line))
  392. top += line_spacing
  393. return parts
  394. def _get_bbox(
  395. self,
  396. text: str | bytes,
  397. font: ImageFont.BaseImageFont | None = None,
  398. anchor: str | None = None,
  399. ) -> tuple[float, float, float, float]:
  400. return (font or self.font).getbbox(
  401. text,
  402. self._get_fontmode(),
  403. self.direction,
  404. self.features,
  405. self.language,
  406. self.stroke_width,
  407. anchor,
  408. )
  409. def get_bbox(
  410. self,
  411. xy: tuple[float, float] = (0, 0),
  412. anchor: str | None = None,
  413. align: str = "left",
  414. ) -> tuple[float, float, float, float]:
  415. """
  416. Returns bounding box (in pixels) of text.
  417. Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel
  418. precision. The bounding box includes extra margins for some fonts, e.g. italics
  419. or accents.
  420. :param xy: The anchor coordinates of the text.
  421. :param anchor: The text anchor alignment. Determines the relative location of
  422. the anchor to the text. The default alignment is top left,
  423. specifically ``la`` for horizontal text and ``lt`` for
  424. vertical text. See :ref:`text-anchors` for details.
  425. :param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or
  426. ``"justify"`` determines the relative alignment of lines. Use the
  427. ``anchor`` parameter to specify the alignment to ``xy``.
  428. :return: ``(left, top, right, bottom)`` bounding box
  429. """
  430. bbox: tuple[float, float, float, float] | None = None
  431. for x, y, anchor, text in self._split(xy, anchor, align):
  432. bbox_line = self._get_bbox(text, anchor=anchor)
  433. bbox_line = (
  434. bbox_line[0] + x,
  435. bbox_line[1] + y,
  436. bbox_line[2] + x,
  437. bbox_line[3] + y,
  438. )
  439. if bbox is None:
  440. bbox = bbox_line
  441. else:
  442. bbox = (
  443. min(bbox[0], bbox_line[0]),
  444. min(bbox[1], bbox_line[1]),
  445. max(bbox[2], bbox_line[2]),
  446. max(bbox[3], bbox_line[3]),
  447. )
  448. assert bbox is not None
  449. return bbox