ImageFont.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # PIL raster font management
  6. #
  7. # History:
  8. # 1996-08-07 fl created (experimental)
  9. # 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
  10. # 1999-02-06 fl rewrote most font management stuff in C
  11. # 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
  12. # 2001-02-17 fl added freetype support
  13. # 2001-05-09 fl added TransposedFont wrapper class
  14. # 2002-03-04 fl make sure we have a "L" or "1" font
  15. # 2002-12-04 fl skip non-directory entries in the system path
  16. # 2003-04-29 fl add embedded default font
  17. # 2003-09-27 fl added support for truetype charmap encodings
  18. #
  19. # Todo:
  20. # Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
  21. #
  22. # Copyright (c) 1997-2003 by Secret Labs AB
  23. # Copyright (c) 1996-2003 by Fredrik Lundh
  24. #
  25. # See the README file for information on usage and redistribution.
  26. #
  27. import base64
  28. import os
  29. import sys
  30. import warnings
  31. from enum import IntEnum
  32. from io import BytesIO
  33. from . import Image
  34. from ._deprecate import deprecate
  35. from ._util import is_directory, is_path
  36. class Layout(IntEnum):
  37. BASIC = 0
  38. RAQM = 1
  39. def __getattr__(name):
  40. for enum, prefix in {Layout: "LAYOUT_"}.items():
  41. if name.startswith(prefix):
  42. name = name[len(prefix) :]
  43. if name in enum.__members__:
  44. deprecate(f"{prefix}{name}", 10, f"{enum.__name__}.{name}")
  45. return enum[name]
  46. raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
  47. class _ImagingFtNotInstalled:
  48. # module placeholder
  49. def __getattr__(self, id):
  50. raise ImportError("The _imagingft C module is not installed")
  51. try:
  52. from . import _imagingft as core
  53. except ImportError:
  54. core = _ImagingFtNotInstalled()
  55. _UNSPECIFIED = object()
  56. # FIXME: add support for pilfont2 format (see FontFile.py)
  57. # --------------------------------------------------------------------
  58. # Font metrics format:
  59. # "PILfont" LF
  60. # fontdescriptor LF
  61. # (optional) key=value... LF
  62. # "DATA" LF
  63. # binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
  64. #
  65. # To place a character, cut out srcbox and paste at dstbox,
  66. # relative to the character position. Then move the character
  67. # position according to dx, dy.
  68. # --------------------------------------------------------------------
  69. class ImageFont:
  70. """PIL font wrapper"""
  71. def _load_pilfont(self, filename):
  72. with open(filename, "rb") as fp:
  73. image = None
  74. for ext in (".png", ".gif", ".pbm"):
  75. if image:
  76. image.close()
  77. try:
  78. fullname = os.path.splitext(filename)[0] + ext
  79. image = Image.open(fullname)
  80. except Exception:
  81. pass
  82. else:
  83. if image and image.mode in ("1", "L"):
  84. break
  85. else:
  86. if image:
  87. image.close()
  88. raise OSError("cannot find glyph data file")
  89. self.file = fullname
  90. self._load_pilfont_data(fp, image)
  91. image.close()
  92. def _load_pilfont_data(self, file, image):
  93. # read PILfont header
  94. if file.readline() != b"PILfont\n":
  95. raise SyntaxError("Not a PILfont file")
  96. file.readline().split(b";")
  97. self.info = [] # FIXME: should be a dictionary
  98. while True:
  99. s = file.readline()
  100. if not s or s == b"DATA\n":
  101. break
  102. self.info.append(s)
  103. # read PILfont metrics
  104. data = file.read(256 * 20)
  105. # check image
  106. if image.mode not in ("1", "L"):
  107. raise TypeError("invalid font image mode")
  108. image.load()
  109. self.font = Image.core.font(image.im, data)
  110. def getsize(self, text, *args, **kwargs):
  111. """
  112. .. deprecated:: 9.2.0
  113. Use :py:meth:`.getbbox` or :py:meth:`.getlength` instead.
  114. Returns width and height (in pixels) of given text.
  115. :param text: Text to measure.
  116. :return: (width, height)
  117. """
  118. deprecate("getsize", 10, "getbbox or getlength")
  119. return self.font.getsize(text)
  120. def getmask(self, text, mode="", *args, **kwargs):
  121. """
  122. Create a bitmap for the text.
  123. If the font uses antialiasing, the bitmap should have mode ``L`` and use a
  124. maximum value of 255. Otherwise, it should have mode ``1``.
  125. :param text: Text to render.
  126. :param mode: Used by some graphics drivers to indicate what mode the
  127. driver prefers; if empty, the renderer may return either
  128. mode. Note that the mode is always a string, to simplify
  129. C-level implementations.
  130. .. versionadded:: 1.1.5
  131. :return: An internal PIL storage memory instance as defined by the
  132. :py:mod:`PIL.Image.core` interface module.
  133. """
  134. return self.font.getmask(text, mode)
  135. def getbbox(self, text, *args, **kwargs):
  136. """
  137. Returns bounding box (in pixels) of given text.
  138. .. versionadded:: 9.2.0
  139. :param text: Text to render.
  140. :param mode: Used by some graphics drivers to indicate what mode the
  141. driver prefers; if empty, the renderer may return either
  142. mode. Note that the mode is always a string, to simplify
  143. C-level implementations.
  144. :return: ``(left, top, right, bottom)`` bounding box
  145. """
  146. width, height = self.font.getsize(text)
  147. return 0, 0, width, height
  148. def getlength(self, text, *args, **kwargs):
  149. """
  150. Returns length (in pixels) of given text.
  151. This is the amount by which following text should be offset.
  152. .. versionadded:: 9.2.0
  153. """
  154. width, height = self.font.getsize(text)
  155. return width
  156. ##
  157. # Wrapper for FreeType fonts. Application code should use the
  158. # <b>truetype</b> factory function to create font objects.
  159. class FreeTypeFont:
  160. """FreeType font wrapper (requires _imagingft service)"""
  161. def __init__(self, font=None, size=10, index=0, encoding="", layout_engine=None):
  162. # FIXME: use service provider instead
  163. self.path = font
  164. self.size = size
  165. self.index = index
  166. self.encoding = encoding
  167. if layout_engine not in (Layout.BASIC, Layout.RAQM):
  168. layout_engine = Layout.BASIC
  169. if core.HAVE_RAQM:
  170. layout_engine = Layout.RAQM
  171. elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
  172. warnings.warn(
  173. "Raqm layout was requested, but Raqm is not available. "
  174. "Falling back to basic layout."
  175. )
  176. layout_engine = Layout.BASIC
  177. self.layout_engine = layout_engine
  178. def load_from_bytes(f):
  179. self.font_bytes = f.read()
  180. self.font = core.getfont(
  181. "", size, index, encoding, self.font_bytes, layout_engine
  182. )
  183. if is_path(font):
  184. if sys.platform == "win32":
  185. font_bytes_path = font if isinstance(font, bytes) else font.encode()
  186. try:
  187. font_bytes_path.decode("ascii")
  188. except UnicodeDecodeError:
  189. # FreeType cannot load fonts with non-ASCII characters on Windows
  190. # So load it into memory first
  191. with open(font, "rb") as f:
  192. load_from_bytes(f)
  193. return
  194. self.font = core.getfont(
  195. font, size, index, encoding, layout_engine=layout_engine
  196. )
  197. else:
  198. load_from_bytes(font)
  199. def __getstate__(self):
  200. return [self.path, self.size, self.index, self.encoding, self.layout_engine]
  201. def __setstate__(self, state):
  202. path, size, index, encoding, layout_engine = state
  203. self.__init__(path, size, index, encoding, layout_engine)
  204. def _multiline_split(self, text):
  205. split_character = "\n" if isinstance(text, str) else b"\n"
  206. return text.split(split_character)
  207. def getname(self):
  208. """
  209. :return: A tuple of the font family (e.g. Helvetica) and the font style
  210. (e.g. Bold)
  211. """
  212. return self.font.family, self.font.style
  213. def getmetrics(self):
  214. """
  215. :return: A tuple of the font ascent (the distance from the baseline to
  216. the highest outline point) and descent (the distance from the
  217. baseline to the lowest outline point, a negative value)
  218. """
  219. return self.font.ascent, self.font.descent
  220. def getlength(self, text, mode="", direction=None, features=None, language=None):
  221. """
  222. Returns length (in pixels with 1/64 precision) of given text when rendered
  223. in font with provided direction, features, and language.
  224. This is the amount by which following text should be offset.
  225. Text bounding box may extend past the length in some fonts,
  226. e.g. when using italics or accents.
  227. The result is returned as a float; it is a whole number if using basic layout.
  228. Note that the sum of two lengths may not equal the length of a concatenated
  229. string due to kerning. If you need to adjust for kerning, include the following
  230. character and subtract its length.
  231. For example, instead of
  232. .. code-block:: python
  233. hello = font.getlength("Hello")
  234. world = font.getlength("World")
  235. hello_world = hello + world # not adjusted for kerning
  236. assert hello_world == font.getlength("HelloWorld") # may fail
  237. use
  238. .. code-block:: python
  239. hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
  240. world = font.getlength("World")
  241. hello_world = hello + world # adjusted for kerning
  242. assert hello_world == font.getlength("HelloWorld") # True
  243. or disable kerning with (requires libraqm)
  244. .. code-block:: python
  245. hello = draw.textlength("Hello", font, features=["-kern"])
  246. world = draw.textlength("World", font, features=["-kern"])
  247. hello_world = hello + world # kerning is disabled, no need to adjust
  248. assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
  249. .. versionadded:: 8.0.0
  250. :param text: Text to measure.
  251. :param mode: Used by some graphics drivers to indicate what mode the
  252. driver prefers; if empty, the renderer may return either
  253. mode. Note that the mode is always a string, to simplify
  254. C-level implementations.
  255. :param direction: Direction of the text. It can be 'rtl' (right to
  256. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  257. Requires libraqm.
  258. :param features: A list of OpenType font features to be used during text
  259. layout. This is usually used to turn on optional
  260. font features that are not enabled by default,
  261. for example 'dlig' or 'ss01', but can be also
  262. used to turn off default font features for
  263. example '-liga' to disable ligatures or '-kern'
  264. to disable kerning. To get all supported
  265. features, see
  266. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  267. Requires libraqm.
  268. :param language: Language of the text. Different languages may use
  269. different glyph shapes or ligatures. This parameter tells
  270. the font which language the text is in, and to apply the
  271. correct substitutions as appropriate, if available.
  272. It should be a `BCP 47 language code
  273. <https://www.w3.org/International/articles/language-tags/>`_
  274. Requires libraqm.
  275. :return: Width for horizontal, height for vertical text.
  276. """
  277. return self.font.getlength(text, mode, direction, features, language) / 64
  278. def getbbox(
  279. self,
  280. text,
  281. mode="",
  282. direction=None,
  283. features=None,
  284. language=None,
  285. stroke_width=0,
  286. anchor=None,
  287. ):
  288. """
  289. Returns bounding box (in pixels) of given text relative to given anchor
  290. when rendered in font with provided direction, features, and language.
  291. Use :py:meth:`getlength()` to get the offset of following text with
  292. 1/64 pixel precision. The bounding box includes extra margins for
  293. some fonts, e.g. italics or accents.
  294. .. versionadded:: 8.0.0
  295. :param text: Text to render.
  296. :param mode: Used by some graphics drivers to indicate what mode the
  297. driver prefers; if empty, the renderer may return either
  298. mode. Note that the mode is always a string, to simplify
  299. C-level implementations.
  300. :param direction: Direction of the text. It can be 'rtl' (right to
  301. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  302. Requires libraqm.
  303. :param features: A list of OpenType font features to be used during text
  304. layout. This is usually used to turn on optional
  305. font features that are not enabled by default,
  306. for example 'dlig' or 'ss01', but can be also
  307. used to turn off default font features for
  308. example '-liga' to disable ligatures or '-kern'
  309. to disable kerning. To get all supported
  310. features, see
  311. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  312. Requires libraqm.
  313. :param language: Language of the text. Different languages may use
  314. different glyph shapes or ligatures. This parameter tells
  315. the font which language the text is in, and to apply the
  316. correct substitutions as appropriate, if available.
  317. It should be a `BCP 47 language code
  318. <https://www.w3.org/International/articles/language-tags/>`_
  319. Requires libraqm.
  320. :param stroke_width: The width of the text stroke.
  321. :param anchor: The text anchor alignment. Determines the relative location of
  322. the anchor to the text. The default alignment is top left.
  323. See :ref:`text-anchors` for valid values.
  324. :return: ``(left, top, right, bottom)`` bounding box
  325. """
  326. size, offset = self.font.getsize(
  327. text, mode, direction, features, language, anchor
  328. )
  329. left, top = offset[0] - stroke_width, offset[1] - stroke_width
  330. width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
  331. return left, top, left + width, top + height
  332. def getsize(
  333. self,
  334. text,
  335. direction=None,
  336. features=None,
  337. language=None,
  338. stroke_width=0,
  339. ):
  340. """
  341. .. deprecated:: 9.2.0
  342. Use :py:meth:`getlength()` to measure the offset of following text with
  343. 1/64 pixel precision.
  344. Use :py:meth:`getbbox()` to get the exact bounding box based on an anchor.
  345. Returns width and height (in pixels) of given text if rendered in font with
  346. provided direction, features, and language.
  347. .. note:: For historical reasons this function measures text height from
  348. the ascender line instead of the top, see :ref:`text-anchors`.
  349. If you wish to measure text height from the top, it is recommended
  350. to use the bottom value of :meth:`getbbox` with ``anchor='lt'`` instead.
  351. :param text: Text to measure.
  352. :param direction: Direction of the text. It can be 'rtl' (right to
  353. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  354. Requires libraqm.
  355. .. versionadded:: 4.2.0
  356. :param features: A list of OpenType font features to be used during text
  357. layout. This is usually used to turn on optional
  358. font features that are not enabled by default,
  359. for example 'dlig' or 'ss01', but can be also
  360. used to turn off default font features for
  361. example '-liga' to disable ligatures or '-kern'
  362. to disable kerning. To get all supported
  363. features, see
  364. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  365. Requires libraqm.
  366. .. versionadded:: 4.2.0
  367. :param language: Language of the text. Different languages may use
  368. different glyph shapes or ligatures. This parameter tells
  369. the font which language the text is in, and to apply the
  370. correct substitutions as appropriate, if available.
  371. It should be a `BCP 47 language code
  372. <https://www.w3.org/International/articles/language-tags/>`_
  373. Requires libraqm.
  374. .. versionadded:: 6.0.0
  375. :param stroke_width: The width of the text stroke.
  376. .. versionadded:: 6.2.0
  377. :return: (width, height)
  378. """
  379. deprecate("getsize", 10, "getbbox or getlength")
  380. # vertical offset is added for historical reasons
  381. # see https://github.com/python-pillow/Pillow/pull/4910#discussion_r486682929
  382. size, offset = self.font.getsize(text, "L", direction, features, language)
  383. return (
  384. size[0] + stroke_width * 2,
  385. size[1] + stroke_width * 2 + offset[1],
  386. )
  387. def getsize_multiline(
  388. self,
  389. text,
  390. direction=None,
  391. spacing=4,
  392. features=None,
  393. language=None,
  394. stroke_width=0,
  395. ):
  396. """
  397. .. deprecated:: 9.2.0
  398. Use :py:meth:`.ImageDraw.multiline_textbbox` instead.
  399. Returns width and height (in pixels) of given text if rendered in font
  400. with provided direction, features, and language, while respecting
  401. newline characters.
  402. :param text: Text to measure.
  403. :param direction: Direction of the text. It can be 'rtl' (right to
  404. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  405. Requires libraqm.
  406. :param spacing: The vertical gap between lines, defaulting to 4 pixels.
  407. :param features: A list of OpenType font features to be used during text
  408. layout. This is usually used to turn on optional
  409. font features that are not enabled by default,
  410. for example 'dlig' or 'ss01', but can be also
  411. used to turn off default font features for
  412. example '-liga' to disable ligatures or '-kern'
  413. to disable kerning. To get all supported
  414. features, see
  415. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  416. Requires libraqm.
  417. :param language: Language of the text. Different languages may use
  418. different glyph shapes or ligatures. This parameter tells
  419. the font which language the text is in, and to apply the
  420. correct substitutions as appropriate, if available.
  421. It should be a `BCP 47 language code
  422. <https://www.w3.org/International/articles/language-tags/>`_
  423. Requires libraqm.
  424. .. versionadded:: 6.0.0
  425. :param stroke_width: The width of the text stroke.
  426. .. versionadded:: 6.2.0
  427. :return: (width, height)
  428. """
  429. deprecate("getsize_multiline", 10, "ImageDraw.multiline_textbbox")
  430. max_width = 0
  431. lines = self._multiline_split(text)
  432. with warnings.catch_warnings():
  433. warnings.filterwarnings("ignore", category=DeprecationWarning)
  434. line_spacing = self.getsize("A", stroke_width=stroke_width)[1] + spacing
  435. for line in lines:
  436. line_width, line_height = self.getsize(
  437. line, direction, features, language, stroke_width
  438. )
  439. max_width = max(max_width, line_width)
  440. return max_width, len(lines) * line_spacing - spacing
  441. def getoffset(self, text):
  442. """
  443. .. deprecated:: 9.2.0
  444. Use :py:meth:`.getbbox` instead.
  445. Returns the offset of given text. This is the gap between the
  446. starting coordinate and the first marking. Note that this gap is
  447. included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`.
  448. :param text: Text to measure.
  449. :return: A tuple of the x and y offset
  450. """
  451. deprecate("getoffset", 10, "getbbox")
  452. return self.font.getsize(text)[1]
  453. def getmask(
  454. self,
  455. text,
  456. mode="",
  457. direction=None,
  458. features=None,
  459. language=None,
  460. stroke_width=0,
  461. anchor=None,
  462. ink=0,
  463. ):
  464. """
  465. Create a bitmap for the text.
  466. If the font uses antialiasing, the bitmap should have mode ``L`` and use a
  467. maximum value of 255. If the font has embedded color data, the bitmap
  468. should have mode ``RGBA``. Otherwise, it should have mode ``1``.
  469. :param text: Text to render.
  470. :param mode: Used by some graphics drivers to indicate what mode the
  471. driver prefers; if empty, the renderer may return either
  472. mode. Note that the mode is always a string, to simplify
  473. C-level implementations.
  474. .. versionadded:: 1.1.5
  475. :param direction: Direction of the text. It can be 'rtl' (right to
  476. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  477. Requires libraqm.
  478. .. versionadded:: 4.2.0
  479. :param features: A list of OpenType font features to be used during text
  480. layout. This is usually used to turn on optional
  481. font features that are not enabled by default,
  482. for example 'dlig' or 'ss01', but can be also
  483. used to turn off default font features for
  484. example '-liga' to disable ligatures or '-kern'
  485. to disable kerning. To get all supported
  486. features, see
  487. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  488. Requires libraqm.
  489. .. versionadded:: 4.2.0
  490. :param language: Language of the text. Different languages may use
  491. different glyph shapes or ligatures. This parameter tells
  492. the font which language the text is in, and to apply the
  493. correct substitutions as appropriate, if available.
  494. It should be a `BCP 47 language code
  495. <https://www.w3.org/International/articles/language-tags/>`_
  496. Requires libraqm.
  497. .. versionadded:: 6.0.0
  498. :param stroke_width: The width of the text stroke.
  499. .. versionadded:: 6.2.0
  500. :param anchor: The text anchor alignment. Determines the relative location of
  501. the anchor to the text. The default alignment is top left.
  502. See :ref:`text-anchors` for valid values.
  503. .. versionadded:: 8.0.0
  504. :param ink: Foreground ink for rendering in RGBA mode.
  505. .. versionadded:: 8.0.0
  506. :return: An internal PIL storage memory instance as defined by the
  507. :py:mod:`PIL.Image.core` interface module.
  508. """
  509. return self.getmask2(
  510. text,
  511. mode,
  512. direction=direction,
  513. features=features,
  514. language=language,
  515. stroke_width=stroke_width,
  516. anchor=anchor,
  517. ink=ink,
  518. )[0]
  519. def getmask2(
  520. self,
  521. text,
  522. mode="",
  523. fill=_UNSPECIFIED,
  524. direction=None,
  525. features=None,
  526. language=None,
  527. stroke_width=0,
  528. anchor=None,
  529. ink=0,
  530. *args,
  531. **kwargs,
  532. ):
  533. """
  534. Create a bitmap for the text.
  535. If the font uses antialiasing, the bitmap should have mode ``L`` and use a
  536. maximum value of 255. If the font has embedded color data, the bitmap
  537. should have mode ``RGBA``. Otherwise, it should have mode ``1``.
  538. :param text: Text to render.
  539. :param mode: Used by some graphics drivers to indicate what mode the
  540. driver prefers; if empty, the renderer may return either
  541. mode. Note that the mode is always a string, to simplify
  542. C-level implementations.
  543. .. versionadded:: 1.1.5
  544. :param fill: Optional fill function. By default, an internal Pillow function
  545. will be used.
  546. Deprecated. This parameter will be removed in Pillow 10
  547. (2023-07-01).
  548. :param direction: Direction of the text. It can be 'rtl' (right to
  549. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  550. Requires libraqm.
  551. .. versionadded:: 4.2.0
  552. :param features: A list of OpenType font features to be used during text
  553. layout. This is usually used to turn on optional
  554. font features that are not enabled by default,
  555. for example 'dlig' or 'ss01', but can be also
  556. used to turn off default font features for
  557. example '-liga' to disable ligatures or '-kern'
  558. to disable kerning. To get all supported
  559. features, see
  560. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  561. Requires libraqm.
  562. .. versionadded:: 4.2.0
  563. :param language: Language of the text. Different languages may use
  564. different glyph shapes or ligatures. This parameter tells
  565. the font which language the text is in, and to apply the
  566. correct substitutions as appropriate, if available.
  567. It should be a `BCP 47 language code
  568. <https://www.w3.org/International/articles/language-tags/>`_
  569. Requires libraqm.
  570. .. versionadded:: 6.0.0
  571. :param stroke_width: The width of the text stroke.
  572. .. versionadded:: 6.2.0
  573. :param anchor: The text anchor alignment. Determines the relative location of
  574. the anchor to the text. The default alignment is top left.
  575. See :ref:`text-anchors` for valid values.
  576. .. versionadded:: 8.0.0
  577. :param ink: Foreground ink for rendering in RGBA mode.
  578. .. versionadded:: 8.0.0
  579. :return: A tuple of an internal PIL storage memory instance as defined by the
  580. :py:mod:`PIL.Image.core` interface module, and the text offset, the
  581. gap between the starting coordinate and the first marking
  582. """
  583. if fill is _UNSPECIFIED:
  584. fill = Image.core.fill
  585. else:
  586. deprecate("fill", 10)
  587. size, offset = self.font.getsize(
  588. text, mode, direction, features, language, anchor
  589. )
  590. size = size[0] + stroke_width * 2, size[1] + stroke_width * 2
  591. offset = offset[0] - stroke_width, offset[1] - stroke_width
  592. Image._decompression_bomb_check(size)
  593. im = fill("RGBA" if mode == "RGBA" else "L", size, 0)
  594. self.font.render(
  595. text, im.id, mode, direction, features, language, stroke_width, ink
  596. )
  597. return im, offset
  598. def font_variant(
  599. self, font=None, size=None, index=None, encoding=None, layout_engine=None
  600. ):
  601. """
  602. Create a copy of this FreeTypeFont object,
  603. using any specified arguments to override the settings.
  604. Parameters are identical to the parameters used to initialize this
  605. object.
  606. :return: A FreeTypeFont object.
  607. """
  608. if font is None:
  609. try:
  610. font = BytesIO(self.font_bytes)
  611. except AttributeError:
  612. font = self.path
  613. return FreeTypeFont(
  614. font=font,
  615. size=self.size if size is None else size,
  616. index=self.index if index is None else index,
  617. encoding=self.encoding if encoding is None else encoding,
  618. layout_engine=layout_engine or self.layout_engine,
  619. )
  620. def get_variation_names(self):
  621. """
  622. :returns: A list of the named styles in a variation font.
  623. :exception OSError: If the font is not a variation font.
  624. """
  625. try:
  626. names = self.font.getvarnames()
  627. except AttributeError as e:
  628. raise NotImplementedError("FreeType 2.9.1 or greater is required") from e
  629. return [name.replace(b"\x00", b"") for name in names]
  630. def set_variation_by_name(self, name):
  631. """
  632. :param name: The name of the style.
  633. :exception OSError: If the font is not a variation font.
  634. """
  635. names = self.get_variation_names()
  636. if not isinstance(name, bytes):
  637. name = name.encode()
  638. index = names.index(name)
  639. if index == getattr(self, "_last_variation_index", None):
  640. # When the same name is set twice in a row,
  641. # there is an 'unknown freetype error'
  642. # https://savannah.nongnu.org/bugs/?56186
  643. return
  644. self._last_variation_index = index
  645. self.font.setvarname(index)
  646. def get_variation_axes(self):
  647. """
  648. :returns: A list of the axes in a variation font.
  649. :exception OSError: If the font is not a variation font.
  650. """
  651. try:
  652. axes = self.font.getvaraxes()
  653. except AttributeError as e:
  654. raise NotImplementedError("FreeType 2.9.1 or greater is required") from e
  655. for axis in axes:
  656. axis["name"] = axis["name"].replace(b"\x00", b"")
  657. return axes
  658. def set_variation_by_axes(self, axes):
  659. """
  660. :param axes: A list of values for each axis.
  661. :exception OSError: If the font is not a variation font.
  662. """
  663. try:
  664. self.font.setvaraxes(axes)
  665. except AttributeError as e:
  666. raise NotImplementedError("FreeType 2.9.1 or greater is required") from e
  667. class TransposedFont:
  668. """Wrapper for writing rotated or mirrored text"""
  669. def __init__(self, font, orientation=None):
  670. """
  671. Wrapper that creates a transposed font from any existing font
  672. object.
  673. :param font: A font object.
  674. :param orientation: An optional orientation. If given, this should
  675. be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
  676. Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
  677. Image.Transpose.ROTATE_270.
  678. """
  679. self.font = font
  680. self.orientation = orientation # any 'transpose' argument, or None
  681. def getsize(self, text, *args, **kwargs):
  682. """
  683. .. deprecated:: 9.2.0
  684. Use :py:meth:`.getbbox` or :py:meth:`.getlength` instead.
  685. """
  686. deprecate("getsize", 10, "getbbox or getlength")
  687. with warnings.catch_warnings():
  688. warnings.filterwarnings("ignore", category=DeprecationWarning)
  689. w, h = self.font.getsize(text)
  690. if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
  691. return h, w
  692. return w, h
  693. def getmask(self, text, mode="", *args, **kwargs):
  694. im = self.font.getmask(text, mode, *args, **kwargs)
  695. if self.orientation is not None:
  696. return im.transpose(self.orientation)
  697. return im
  698. def getbbox(self, text, *args, **kwargs):
  699. # TransposedFont doesn't support getmask2, move top-left point to (0, 0)
  700. # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
  701. left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
  702. width = right - left
  703. height = bottom - top
  704. if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
  705. return 0, 0, height, width
  706. return 0, 0, width, height
  707. def getlength(self, text, *args, **kwargs):
  708. if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
  709. raise ValueError(
  710. "text length is undefined for text rotated by 90 or 270 degrees"
  711. )
  712. return self.font.getlength(text, *args, **kwargs)
  713. def load(filename):
  714. """
  715. Load a font file. This function loads a font object from the given
  716. bitmap font file, and returns the corresponding font object.
  717. :param filename: Name of font file.
  718. :return: A font object.
  719. :exception OSError: If the file could not be read.
  720. """
  721. f = ImageFont()
  722. f._load_pilfont(filename)
  723. return f
  724. def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
  725. """
  726. Load a TrueType or OpenType font from a file or file-like object,
  727. and create a font object.
  728. This function loads a font object from the given file or file-like
  729. object, and creates a font object for a font of the given size.
  730. Pillow uses FreeType to open font files. If you are opening many fonts
  731. simultaneously on Windows, be aware that Windows limits the number of files
  732. that can be open in C at once to 512. If you approach that limit, an
  733. ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
  734. This function requires the _imagingft service.
  735. :param font: A filename or file-like object containing a TrueType font.
  736. If the file is not found in this filename, the loader may also
  737. search in other directories, such as the :file:`fonts/`
  738. directory on Windows or :file:`/Library/Fonts/`,
  739. :file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on
  740. macOS.
  741. :param size: The requested size, in pixels.
  742. :param index: Which font face to load (default is first available face).
  743. :param encoding: Which font encoding to use (default is Unicode). Possible
  744. encodings include (see the FreeType documentation for more
  745. information):
  746. * "unic" (Unicode)
  747. * "symb" (Microsoft Symbol)
  748. * "ADOB" (Adobe Standard)
  749. * "ADBE" (Adobe Expert)
  750. * "ADBC" (Adobe Custom)
  751. * "armn" (Apple Roman)
  752. * "sjis" (Shift JIS)
  753. * "gb " (PRC)
  754. * "big5"
  755. * "wans" (Extended Wansung)
  756. * "joha" (Johab)
  757. * "lat1" (Latin-1)
  758. This specifies the character set to use. It does not alter the
  759. encoding of any text provided in subsequent operations.
  760. :param layout_engine: Which layout engine to use, if available:
  761. :data:`.ImageFont.Layout.BASIC` or :data:`.ImageFont.Layout.RAQM`.
  762. You can check support for Raqm layout using
  763. :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
  764. .. versionadded:: 4.2.0
  765. :return: A font object.
  766. :exception OSError: If the file could not be read.
  767. """
  768. def freetype(font):
  769. return FreeTypeFont(font, size, index, encoding, layout_engine)
  770. try:
  771. return freetype(font)
  772. except OSError:
  773. if not is_path(font):
  774. raise
  775. ttf_filename = os.path.basename(font)
  776. dirs = []
  777. if sys.platform == "win32":
  778. # check the windows font repository
  779. # NOTE: must use uppercase WINDIR, to work around bugs in
  780. # 1.5.2's os.environ.get()
  781. windir = os.environ.get("WINDIR")
  782. if windir:
  783. dirs.append(os.path.join(windir, "fonts"))
  784. elif sys.platform in ("linux", "linux2"):
  785. lindirs = os.environ.get("XDG_DATA_DIRS", "")
  786. if not lindirs:
  787. # According to the freedesktop spec, XDG_DATA_DIRS should
  788. # default to /usr/share
  789. lindirs = "/usr/share"
  790. dirs += [os.path.join(lindir, "fonts") for lindir in lindirs.split(":")]
  791. elif sys.platform == "darwin":
  792. dirs += [
  793. "/Library/Fonts",
  794. "/System/Library/Fonts",
  795. os.path.expanduser("~/Library/Fonts"),
  796. ]
  797. ext = os.path.splitext(ttf_filename)[1]
  798. first_font_with_a_different_extension = None
  799. for directory in dirs:
  800. for walkroot, walkdir, walkfilenames in os.walk(directory):
  801. for walkfilename in walkfilenames:
  802. if ext and walkfilename == ttf_filename:
  803. return freetype(os.path.join(walkroot, walkfilename))
  804. elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
  805. fontpath = os.path.join(walkroot, walkfilename)
  806. if os.path.splitext(fontpath)[1] == ".ttf":
  807. return freetype(fontpath)
  808. if not ext and first_font_with_a_different_extension is None:
  809. first_font_with_a_different_extension = fontpath
  810. if first_font_with_a_different_extension:
  811. return freetype(first_font_with_a_different_extension)
  812. raise
  813. def load_path(filename):
  814. """
  815. Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
  816. bitmap font along the Python path.
  817. :param filename: Name of font file.
  818. :return: A font object.
  819. :exception OSError: If the file could not be read.
  820. """
  821. for directory in sys.path:
  822. if is_directory(directory):
  823. if not isinstance(filename, str):
  824. filename = filename.decode("utf-8")
  825. try:
  826. return load(os.path.join(directory, filename))
  827. except OSError:
  828. pass
  829. raise OSError("cannot find font file")
  830. def load_default():
  831. """Load a "better than nothing" default font.
  832. .. versionadded:: 1.1.4
  833. :return: A font object.
  834. """
  835. f = ImageFont()
  836. f._load_pilfont_data(
  837. # courB08
  838. BytesIO(
  839. base64.b64decode(
  840. b"""
  841. UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  842. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  843. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  844. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  845. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  846. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  847. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  848. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  849. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  850. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  851. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  852. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA
  853. BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL
  854. AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA
  855. AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
  856. ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
  857. BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
  858. //kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
  859. AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
  860. AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
  861. ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
  862. AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
  863. /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
  864. AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
  865. AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
  866. AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
  867. BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
  868. AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
  869. 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
  870. AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
  871. +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
  872. ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
  873. BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
  874. AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
  875. AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
  876. AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
  877. BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
  878. //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
  879. AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
  880. AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
  881. mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
  882. AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
  883. AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
  884. AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
  885. Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
  886. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  887. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  888. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  889. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  890. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  891. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  892. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  893. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  894. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  895. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  896. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  897. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
  898. //sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
  899. AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
  900. AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
  901. DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
  902. AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
  903. +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
  904. AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
  905. ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
  906. AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
  907. BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
  908. Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
  909. eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
  910. AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
  911. +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
  912. ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
  913. BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
  914. AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
  915. AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
  916. Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
  917. Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
  918. //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
  919. AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
  920. AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
  921. LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
  922. AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
  923. AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
  924. AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
  925. AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
  926. AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
  927. EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
  928. AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
  929. pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
  930. AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
  931. +QAGAAIAzgAKANUAEw==
  932. """
  933. )
  934. ),
  935. Image.open(
  936. BytesIO(
  937. base64.b64decode(
  938. b"""
  939. iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
  940. Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
  941. M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
  942. LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
  943. IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
  944. Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
  945. NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
  946. in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
  947. SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
  948. AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
  949. y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
  950. ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
  951. lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
  952. /Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
  953. AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
  954. c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
  955. /yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
  956. pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
  957. oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
  958. evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
  959. AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
  960. Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
  961. w7IkEbzhVQAAAABJRU5ErkJggg==
  962. """
  963. )
  964. )
  965. ),
  966. )
  967. return f