ImageText.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from __future__ import annotations
  2. from . import ImageFont
  3. from ._typing import _Ink
  4. class Text:
  5. def __init__(
  6. self,
  7. text: str | bytes,
  8. font: (
  9. ImageFont.ImageFont
  10. | ImageFont.FreeTypeFont
  11. | ImageFont.TransposedFont
  12. | None
  13. ) = None,
  14. mode: str = "RGB",
  15. spacing: float = 4,
  16. direction: str | None = None,
  17. features: list[str] | None = None,
  18. language: str | None = None,
  19. ) -> None:
  20. """
  21. :param text: String to be drawn.
  22. :param font: Either an :py:class:`~PIL.ImageFont.ImageFont` instance,
  23. :py:class:`~PIL.ImageFont.FreeTypeFont` instance,
  24. :py:class:`~PIL.ImageFont.TransposedFont` instance or ``None``. If
  25. ``None``, the default font from :py:meth:`.ImageFont.load_default`
  26. will be used.
  27. :param mode: The image mode this will be used with.
  28. :param spacing: The number of pixels between lines.
  29. :param direction: Direction of the text. It can be ``"rtl"`` (right to left),
  30. ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
  31. Requires libraqm.
  32. :param features: A list of OpenType font features to be used during text
  33. layout. This is usually used to turn on optional font features
  34. that are not enabled by default, for example ``"dlig"`` or
  35. ``"ss01"``, but can be also used to turn off default font
  36. features, for example ``"-liga"`` to disable ligatures or
  37. ``"-kern"`` to disable kerning. To get all supported
  38. features, see `OpenType docs`_.
  39. Requires libraqm.
  40. :param language: Language of the text. Different languages may use
  41. different glyph shapes or ligatures. This parameter tells
  42. the font which language the text is in, and to apply the
  43. correct substitutions as appropriate, if available.
  44. It should be a `BCP 47 language code`_.
  45. Requires libraqm.
  46. """
  47. self.text = text
  48. self.font = font or ImageFont.load_default()
  49. self.mode = mode
  50. self.spacing = spacing
  51. self.direction = direction
  52. self.features = features
  53. self.language = language
  54. self.embedded_color = False
  55. self.stroke_width: float = 0
  56. self.stroke_fill: _Ink | None = None
  57. def embed_color(self) -> None:
  58. """
  59. Use embedded color glyphs (COLR, CBDT, SBIX).
  60. """
  61. if self.mode not in ("RGB", "RGBA"):
  62. msg = "Embedded color supported only in RGB and RGBA modes"
  63. raise ValueError(msg)
  64. self.embedded_color = True
  65. def stroke(self, width: float = 0, fill: _Ink | None = None) -> None:
  66. """
  67. :param width: The width of the text stroke.
  68. :param fill: Color to use for the text stroke when drawing. If not given, will
  69. default to the ``fill`` parameter from
  70. :py:meth:`.ImageDraw.ImageDraw.text`.
  71. """
  72. self.stroke_width = width
  73. self.stroke_fill = fill
  74. def _get_fontmode(self) -> str:
  75. if self.mode in ("1", "P", "I", "F"):
  76. return "1"
  77. elif self.embedded_color:
  78. return "RGBA"
  79. else:
  80. return "L"
  81. def get_length(self):
  82. """
  83. Returns length (in pixels with 1/64 precision) of text.
  84. This is the amount by which following text should be offset.
  85. Text bounding box may extend past the length in some fonts,
  86. e.g. when using italics or accents.
  87. The result is returned as a float; it is a whole number if using basic layout.
  88. Note that the sum of two lengths may not equal the length of a concatenated
  89. string due to kerning. If you need to adjust for kerning, include the following
  90. character and subtract its length.
  91. For example, instead of::
  92. hello = ImageText.Text("Hello", font).get_length()
  93. world = ImageText.Text("World", font).get_length()
  94. helloworld = ImageText.Text("HelloWorld", font).get_length()
  95. assert hello + world == helloworld
  96. use::
  97. hello = (
  98. ImageText.Text("HelloW", font).get_length() -
  99. ImageText.Text("W", font).get_length()
  100. ) # adjusted for kerning
  101. world = ImageText.Text("World", font).get_length()
  102. helloworld = ImageText.Text("HelloWorld", font).get_length()
  103. assert hello + world == helloworld
  104. or disable kerning with (requires libraqm)::
  105. hello = ImageText.Text("Hello", font, features=["-kern"]).get_length()
  106. world = ImageText.Text("World", font, features=["-kern"]).get_length()
  107. helloworld = ImageText.Text(
  108. "HelloWorld", font, features=["-kern"]
  109. ).get_length()
  110. assert hello + world == helloworld
  111. :return: Either width for horizontal text, or height for vertical text.
  112. """
  113. split_character = "\n" if isinstance(self.text, str) else b"\n"
  114. if split_character in self.text:
  115. msg = "can't measure length of multiline text"
  116. raise ValueError(msg)
  117. return self.font.getlength(
  118. self.text,
  119. self._get_fontmode(),
  120. self.direction,
  121. self.features,
  122. self.language,
  123. )
  124. def _split(
  125. self, xy: tuple[float, float], anchor: str | None, align: str
  126. ) -> list[tuple[tuple[float, float], str, str | bytes]]:
  127. if anchor is None:
  128. anchor = "lt" if self.direction == "ttb" else "la"
  129. elif len(anchor) != 2:
  130. msg = "anchor must be a 2 character string"
  131. raise ValueError(msg)
  132. lines = (
  133. self.text.split("\n")
  134. if isinstance(self.text, str)
  135. else self.text.split(b"\n")
  136. )
  137. if len(lines) == 1:
  138. return [(xy, anchor, self.text)]
  139. if anchor[1] in "tb" and self.direction != "ttb":
  140. msg = "anchor not supported for multiline text"
  141. raise ValueError(msg)
  142. fontmode = self._get_fontmode()
  143. line_spacing = (
  144. self.font.getbbox(
  145. "A",
  146. fontmode,
  147. None,
  148. self.features,
  149. self.language,
  150. self.stroke_width,
  151. )[3]
  152. + self.stroke_width
  153. + self.spacing
  154. )
  155. top = xy[1]
  156. parts = []
  157. if self.direction == "ttb":
  158. left = xy[0]
  159. for line in lines:
  160. parts.append(((left, top), anchor, line))
  161. left += line_spacing
  162. else:
  163. widths = []
  164. max_width: float = 0
  165. for line in lines:
  166. line_width = self.font.getlength(
  167. line, fontmode, self.direction, self.features, self.language
  168. )
  169. widths.append(line_width)
  170. max_width = max(max_width, line_width)
  171. if anchor[1] == "m":
  172. top -= (len(lines) - 1) * line_spacing / 2.0
  173. elif anchor[1] == "d":
  174. top -= (len(lines) - 1) * line_spacing
  175. idx = -1
  176. for line in lines:
  177. left = xy[0]
  178. idx += 1
  179. width_difference = max_width - widths[idx]
  180. # align by align parameter
  181. if align in ("left", "justify"):
  182. pass
  183. elif align == "center":
  184. left += width_difference / 2.0
  185. elif align == "right":
  186. left += width_difference
  187. else:
  188. msg = 'align must be "left", "center", "right" or "justify"'
  189. raise ValueError(msg)
  190. if (
  191. align == "justify"
  192. and width_difference != 0
  193. and idx != len(lines) - 1
  194. ):
  195. words = (
  196. line.split(" ") if isinstance(line, str) else line.split(b" ")
  197. )
  198. if len(words) > 1:
  199. # align left by anchor
  200. if anchor[0] == "m":
  201. left -= max_width / 2.0
  202. elif anchor[0] == "r":
  203. left -= max_width
  204. word_widths = [
  205. self.font.getlength(
  206. word,
  207. fontmode,
  208. self.direction,
  209. self.features,
  210. self.language,
  211. )
  212. for word in words
  213. ]
  214. word_anchor = "l" + anchor[1]
  215. width_difference = max_width - sum(word_widths)
  216. i = 0
  217. for word in words:
  218. parts.append(((left, top), word_anchor, word))
  219. left += word_widths[i] + width_difference / (len(words) - 1)
  220. i += 1
  221. top += line_spacing
  222. continue
  223. # align left by anchor
  224. if anchor[0] == "m":
  225. left -= width_difference / 2.0
  226. elif anchor[0] == "r":
  227. left -= width_difference
  228. parts.append(((left, top), anchor, line))
  229. top += line_spacing
  230. return parts
  231. def get_bbox(
  232. self,
  233. xy: tuple[float, float] = (0, 0),
  234. anchor: str | None = None,
  235. align: str = "left",
  236. ) -> tuple[float, float, float, float]:
  237. """
  238. Returns bounding box (in pixels) of text.
  239. Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel
  240. precision. The bounding box includes extra margins for some fonts, e.g. italics
  241. or accents.
  242. :param xy: The anchor coordinates of the text.
  243. :param anchor: The text anchor alignment. Determines the relative location of
  244. the anchor to the text. The default alignment is top left,
  245. specifically ``la`` for horizontal text and ``lt`` for
  246. vertical text. See :ref:`text-anchors` for details.
  247. :param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or
  248. ``"justify"`` determines the relative alignment of lines. Use the
  249. ``anchor`` parameter to specify the alignment to ``xy``.
  250. :return: ``(left, top, right, bottom)`` bounding box
  251. """
  252. bbox: tuple[float, float, float, float] | None = None
  253. fontmode = self._get_fontmode()
  254. for xy, anchor, line in self._split(xy, anchor, align):
  255. bbox_line = self.font.getbbox(
  256. line,
  257. fontmode,
  258. self.direction,
  259. self.features,
  260. self.language,
  261. self.stroke_width,
  262. anchor,
  263. )
  264. bbox_line = (
  265. bbox_line[0] + xy[0],
  266. bbox_line[1] + xy[1],
  267. bbox_line[2] + xy[0],
  268. bbox_line[3] + xy[1],
  269. )
  270. if bbox is None:
  271. bbox = bbox_line
  272. else:
  273. bbox = (
  274. min(bbox[0], bbox_line[0]),
  275. min(bbox[1], bbox_line[1]),
  276. max(bbox[2], bbox_line[2]),
  277. max(bbox[3], bbox_line[3]),
  278. )
  279. if bbox is None:
  280. return xy[0], xy[1], xy[0], xy[1]
  281. return bbox