ImageFont.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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 os
  28. import sys
  29. from . import Image
  30. from ._util import isDirectory, isPath, py3
  31. LAYOUT_BASIC = 0
  32. LAYOUT_RAQM = 1
  33. class _imagingft_not_installed(object):
  34. # module placeholder
  35. def __getattr__(self, id):
  36. raise ImportError("The _imagingft C module is not installed")
  37. try:
  38. from . import _imagingft as core
  39. except ImportError:
  40. core = _imagingft_not_installed()
  41. # FIXME: add support for pilfont2 format (see FontFile.py)
  42. # --------------------------------------------------------------------
  43. # Font metrics format:
  44. # "PILfont" LF
  45. # fontdescriptor LF
  46. # (optional) key=value... LF
  47. # "DATA" LF
  48. # binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
  49. #
  50. # To place a character, cut out srcbox and paste at dstbox,
  51. # relative to the character position. Then move the character
  52. # position according to dx, dy.
  53. # --------------------------------------------------------------------
  54. class ImageFont(object):
  55. "PIL font wrapper"
  56. def _load_pilfont(self, filename):
  57. with open(filename, "rb") as fp:
  58. for ext in (".png", ".gif", ".pbm"):
  59. try:
  60. fullname = os.path.splitext(filename)[0] + ext
  61. image = Image.open(fullname)
  62. except Exception:
  63. pass
  64. else:
  65. if image and image.mode in ("1", "L"):
  66. break
  67. else:
  68. raise IOError("cannot find glyph data file")
  69. self.file = fullname
  70. return self._load_pilfont_data(fp, image)
  71. def _load_pilfont_data(self, file, image):
  72. # read PILfont header
  73. if file.readline() != b"PILfont\n":
  74. raise SyntaxError("Not a PILfont file")
  75. file.readline().split(b";")
  76. self.info = [] # FIXME: should be a dictionary
  77. while True:
  78. s = file.readline()
  79. if not s or s == b"DATA\n":
  80. break
  81. self.info.append(s)
  82. # read PILfont metrics
  83. data = file.read(256 * 20)
  84. # check image
  85. if image.mode not in ("1", "L"):
  86. raise TypeError("invalid font image mode")
  87. image.load()
  88. self.font = Image.core.font(image.im, data)
  89. def getsize(self, text, *args, **kwargs):
  90. """
  91. Returns width and height (in pixels) of given text.
  92. :param text: Text to measure.
  93. :return: (width, height)
  94. """
  95. return self.font.getsize(text)
  96. def getmask(self, text, mode="", *args, **kwargs):
  97. """
  98. Create a bitmap for the text.
  99. If the font uses antialiasing, the bitmap should have mode ``L`` and use a
  100. maximum value of 255. Otherwise, it should have mode ``1``.
  101. :param text: Text to render.
  102. :param mode: Used by some graphics drivers to indicate what mode the
  103. driver prefers; if empty, the renderer may return either
  104. mode. Note that the mode is always a string, to simplify
  105. C-level implementations.
  106. .. versionadded:: 1.1.5
  107. :return: An internal PIL storage memory instance as defined by the
  108. :py:mod:`PIL.Image.core` interface module.
  109. """
  110. return self.font.getmask(text, mode)
  111. ##
  112. # Wrapper for FreeType fonts. Application code should use the
  113. # <b>truetype</b> factory function to create font objects.
  114. class FreeTypeFont(object):
  115. "FreeType font wrapper (requires _imagingft service)"
  116. def __init__(self, font=None, size=10, index=0, encoding="", layout_engine=None):
  117. # FIXME: use service provider instead
  118. self.path = font
  119. self.size = size
  120. self.index = index
  121. self.encoding = encoding
  122. if layout_engine not in (LAYOUT_BASIC, LAYOUT_RAQM):
  123. layout_engine = LAYOUT_BASIC
  124. if core.HAVE_RAQM:
  125. layout_engine = LAYOUT_RAQM
  126. elif layout_engine == LAYOUT_RAQM and not core.HAVE_RAQM:
  127. layout_engine = LAYOUT_BASIC
  128. self.layout_engine = layout_engine
  129. def load_from_bytes(f):
  130. self.font_bytes = f.read()
  131. self.font = core.getfont(
  132. "", size, index, encoding, self.font_bytes, layout_engine
  133. )
  134. if isPath(font):
  135. if sys.platform == "win32":
  136. font_bytes_path = font if isinstance(font, bytes) else font.encode()
  137. try:
  138. font_bytes_path.decode("ascii")
  139. except UnicodeDecodeError:
  140. # FreeType cannot load fonts with non-ASCII characters on Windows
  141. # So load it into memory first
  142. with open(font, "rb") as f:
  143. load_from_bytes(f)
  144. return
  145. self.font = core.getfont(
  146. font, size, index, encoding, layout_engine=layout_engine
  147. )
  148. else:
  149. load_from_bytes(font)
  150. def _multiline_split(self, text):
  151. split_character = "\n" if isinstance(text, str) else b"\n"
  152. return text.split(split_character)
  153. def getname(self):
  154. """
  155. :return: A tuple of the font family (e.g. Helvetica) and the font style
  156. (e.g. Bold)
  157. """
  158. return self.font.family, self.font.style
  159. def getmetrics(self):
  160. """
  161. :return: A tuple of the font ascent (the distance from the baseline to
  162. the highest outline point) and descent (the distance from the
  163. baseline to the lowest outline point, a negative value)
  164. """
  165. return self.font.ascent, self.font.descent
  166. def getsize(
  167. self, text, direction=None, features=None, language=None, stroke_width=0
  168. ):
  169. """
  170. Returns width and height (in pixels) of given text if rendered in font with
  171. provided direction, features, and language.
  172. :param text: Text to measure.
  173. :param direction: Direction of the text. It can be 'rtl' (right to
  174. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  175. Requires libraqm.
  176. .. versionadded:: 4.2.0
  177. :param features: A list of OpenType font features to be used during text
  178. layout. This is usually used to turn on optional
  179. font features that are not enabled by default,
  180. for example 'dlig' or 'ss01', but can be also
  181. used to turn off default font features for
  182. example '-liga' to disable ligatures or '-kern'
  183. to disable kerning. To get all supported
  184. features, see
  185. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  186. Requires libraqm.
  187. .. versionadded:: 4.2.0
  188. :param language: Language of the text. Different languages may use
  189. different glyph shapes or ligatures. This parameter tells
  190. the font which language the text is in, and to apply the
  191. correct substitutions as appropriate, if available.
  192. It should be a `BCP 47 language code
  193. <https://www.w3.org/International/articles/language-tags/>`
  194. Requires libraqm.
  195. .. versionadded:: 6.0.0
  196. :param stroke_width: The width of the text stroke.
  197. .. versionadded:: 6.2.0
  198. :return: (width, height)
  199. """
  200. size, offset = self.font.getsize(text, direction, features, language)
  201. return (
  202. size[0] + stroke_width * 2 + offset[0],
  203. size[1] + stroke_width * 2 + offset[1],
  204. )
  205. def getsize_multiline(
  206. self,
  207. text,
  208. direction=None,
  209. spacing=4,
  210. features=None,
  211. language=None,
  212. stroke_width=0,
  213. ):
  214. """
  215. Returns width and height (in pixels) of given text if rendered in font
  216. with provided direction, features, and language, while respecting
  217. newline characters.
  218. :param text: Text to measure.
  219. :param direction: Direction of the text. It can be 'rtl' (right to
  220. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  221. Requires libraqm.
  222. :param spacing: The vertical gap between lines, defaulting to 4 pixels.
  223. :param features: A list of OpenType font features to be used during text
  224. layout. This is usually used to turn on optional
  225. font features that are not enabled by default,
  226. for example 'dlig' or 'ss01', but can be also
  227. used to turn off default font features for
  228. example '-liga' to disable ligatures or '-kern'
  229. to disable kerning. To get all supported
  230. features, see
  231. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  232. Requires libraqm.
  233. :param language: Language of the text. Different languages may use
  234. different glyph shapes or ligatures. This parameter tells
  235. the font which language the text is in, and to apply the
  236. correct substitutions as appropriate, if available.
  237. It should be a `BCP 47 language code
  238. <https://www.w3.org/International/articles/language-tags/>`
  239. Requires libraqm.
  240. .. versionadded:: 6.0.0
  241. :param stroke_width: The width of the text stroke.
  242. .. versionadded:: 6.2.0
  243. :return: (width, height)
  244. """
  245. max_width = 0
  246. lines = self._multiline_split(text)
  247. line_spacing = self.getsize("A", stroke_width=stroke_width)[1] + spacing
  248. for line in lines:
  249. line_width, line_height = self.getsize(
  250. line, direction, features, language, stroke_width
  251. )
  252. max_width = max(max_width, line_width)
  253. return max_width, len(lines) * line_spacing - spacing
  254. def getoffset(self, text):
  255. """
  256. Returns the offset of given text. This is the gap between the
  257. starting coordinate and the first marking. Note that this gap is
  258. included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`.
  259. :param text: Text to measure.
  260. :return: A tuple of the x and y offset
  261. """
  262. return self.font.getsize(text)[1]
  263. def getmask(
  264. self,
  265. text,
  266. mode="",
  267. direction=None,
  268. features=None,
  269. language=None,
  270. stroke_width=0,
  271. ):
  272. """
  273. Create a bitmap for the text.
  274. If the font uses antialiasing, the bitmap should have mode ``L`` and use a
  275. maximum value of 255. Otherwise, it should have mode ``1``.
  276. :param text: Text to render.
  277. :param mode: Used by some graphics drivers to indicate what mode the
  278. driver prefers; if empty, the renderer may return either
  279. mode. Note that the mode is always a string, to simplify
  280. C-level implementations.
  281. .. versionadded:: 1.1.5
  282. :param direction: Direction of the text. It can be 'rtl' (right to
  283. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  284. Requires libraqm.
  285. .. versionadded:: 4.2.0
  286. :param features: A list of OpenType font features to be used during text
  287. layout. This is usually used to turn on optional
  288. font features that are not enabled by default,
  289. for example 'dlig' or 'ss01', but can be also
  290. used to turn off default font features for
  291. example '-liga' to disable ligatures or '-kern'
  292. to disable kerning. To get all supported
  293. features, see
  294. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  295. Requires libraqm.
  296. .. versionadded:: 4.2.0
  297. :param language: Language of the text. Different languages may use
  298. different glyph shapes or ligatures. This parameter tells
  299. the font which language the text is in, and to apply the
  300. correct substitutions as appropriate, if available.
  301. It should be a `BCP 47 language code
  302. <https://www.w3.org/International/articles/language-tags/>`
  303. Requires libraqm.
  304. .. versionadded:: 6.0.0
  305. :param stroke_width: The width of the text stroke.
  306. .. versionadded:: 6.2.0
  307. :return: An internal PIL storage memory instance as defined by the
  308. :py:mod:`PIL.Image.core` interface module.
  309. """
  310. return self.getmask2(
  311. text,
  312. mode,
  313. direction=direction,
  314. features=features,
  315. language=language,
  316. stroke_width=stroke_width,
  317. )[0]
  318. def getmask2(
  319. self,
  320. text,
  321. mode="",
  322. fill=Image.core.fill,
  323. direction=None,
  324. features=None,
  325. language=None,
  326. stroke_width=0,
  327. *args,
  328. **kwargs
  329. ):
  330. """
  331. Create a bitmap for the text.
  332. If the font uses antialiasing, the bitmap should have mode ``L`` and use a
  333. maximum value of 255. Otherwise, it should have mode ``1``.
  334. :param text: Text to render.
  335. :param mode: Used by some graphics drivers to indicate what mode the
  336. driver prefers; if empty, the renderer may return either
  337. mode. Note that the mode is always a string, to simplify
  338. C-level implementations.
  339. .. versionadded:: 1.1.5
  340. :param direction: Direction of the text. It can be 'rtl' (right to
  341. left), 'ltr' (left to right) or 'ttb' (top to bottom).
  342. Requires libraqm.
  343. .. versionadded:: 4.2.0
  344. :param features: A list of OpenType font features to be used during text
  345. layout. This is usually used to turn on optional
  346. font features that are not enabled by default,
  347. for example 'dlig' or 'ss01', but can be also
  348. used to turn off default font features for
  349. example '-liga' to disable ligatures or '-kern'
  350. to disable kerning. To get all supported
  351. features, see
  352. https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
  353. Requires libraqm.
  354. .. versionadded:: 4.2.0
  355. :param language: Language of the text. Different languages may use
  356. different glyph shapes or ligatures. This parameter tells
  357. the font which language the text is in, and to apply the
  358. correct substitutions as appropriate, if available.
  359. It should be a `BCP 47 language code
  360. <https://www.w3.org/International/articles/language-tags/>`
  361. Requires libraqm.
  362. .. versionadded:: 6.0.0
  363. :param stroke_width: The width of the text stroke.
  364. .. versionadded:: 6.2.0
  365. :return: A tuple of an internal PIL storage memory instance as defined by the
  366. :py:mod:`PIL.Image.core` interface module, and the text offset, the
  367. gap between the starting coordinate and the first marking
  368. """
  369. size, offset = self.font.getsize(text, direction, features, language)
  370. size = size[0] + stroke_width * 2, size[1] + stroke_width * 2
  371. im = fill("L", size, 0)
  372. self.font.render(
  373. text, im.id, mode == "1", direction, features, language, stroke_width
  374. )
  375. return im, offset
  376. def font_variant(
  377. self, font=None, size=None, index=None, encoding=None, layout_engine=None
  378. ):
  379. """
  380. Create a copy of this FreeTypeFont object,
  381. using any specified arguments to override the settings.
  382. Parameters are identical to the parameters used to initialize this
  383. object.
  384. :return: A FreeTypeFont object.
  385. """
  386. return FreeTypeFont(
  387. font=self.path if font is None else font,
  388. size=self.size if size is None else size,
  389. index=self.index if index is None else index,
  390. encoding=self.encoding if encoding is None else encoding,
  391. layout_engine=layout_engine or self.layout_engine,
  392. )
  393. def get_variation_names(self):
  394. """
  395. :returns: A list of the named styles in a variation font.
  396. :exception IOError: If the font is not a variation font.
  397. """
  398. try:
  399. names = self.font.getvarnames()
  400. except AttributeError:
  401. raise NotImplementedError("FreeType 2.9.1 or greater is required")
  402. return [name.replace(b"\x00", b"") for name in names]
  403. def set_variation_by_name(self, name):
  404. """
  405. :param name: The name of the style.
  406. :exception IOError: If the font is not a variation font.
  407. """
  408. names = self.get_variation_names()
  409. if not isinstance(name, bytes):
  410. name = name.encode()
  411. index = names.index(name)
  412. if index == getattr(self, "_last_variation_index", None):
  413. # When the same name is set twice in a row,
  414. # there is an 'unknown freetype error'
  415. # https://savannah.nongnu.org/bugs/?56186
  416. return
  417. self._last_variation_index = index
  418. self.font.setvarname(index)
  419. def get_variation_axes(self):
  420. """
  421. :returns: A list of the axes in a variation font.
  422. :exception IOError: If the font is not a variation font.
  423. """
  424. try:
  425. axes = self.font.getvaraxes()
  426. except AttributeError:
  427. raise NotImplementedError("FreeType 2.9.1 or greater is required")
  428. for axis in axes:
  429. axis["name"] = axis["name"].replace(b"\x00", b"")
  430. return axes
  431. def set_variation_by_axes(self, axes):
  432. """
  433. :param axes: A list of values for each axis.
  434. :exception IOError: If the font is not a variation font.
  435. """
  436. try:
  437. self.font.setvaraxes(axes)
  438. except AttributeError:
  439. raise NotImplementedError("FreeType 2.9.1 or greater is required")
  440. class TransposedFont(object):
  441. "Wrapper for writing rotated or mirrored text"
  442. def __init__(self, font, orientation=None):
  443. """
  444. Wrapper that creates a transposed font from any existing font
  445. object.
  446. :param font: A font object.
  447. :param orientation: An optional orientation. If given, this should
  448. be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM,
  449. Image.ROTATE_90, Image.ROTATE_180, or Image.ROTATE_270.
  450. """
  451. self.font = font
  452. self.orientation = orientation # any 'transpose' argument, or None
  453. def getsize(self, text, *args, **kwargs):
  454. w, h = self.font.getsize(text)
  455. if self.orientation in (Image.ROTATE_90, Image.ROTATE_270):
  456. return h, w
  457. return w, h
  458. def getmask(self, text, mode="", *args, **kwargs):
  459. im = self.font.getmask(text, mode, *args, **kwargs)
  460. if self.orientation is not None:
  461. return im.transpose(self.orientation)
  462. return im
  463. def load(filename):
  464. """
  465. Load a font file. This function loads a font object from the given
  466. bitmap font file, and returns the corresponding font object.
  467. :param filename: Name of font file.
  468. :return: A font object.
  469. :exception IOError: If the file could not be read.
  470. """
  471. f = ImageFont()
  472. f._load_pilfont(filename)
  473. return f
  474. def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
  475. """
  476. Load a TrueType or OpenType font from a file or file-like object,
  477. and create a font object.
  478. This function loads a font object from the given file or file-like
  479. object, and creates a font object for a font of the given size.
  480. Pillow uses FreeType to open font files. If you are opening many fonts
  481. simultaneously on Windows, be aware that Windows limits the number of files
  482. that can be open in C at once to 512. If you approach that limit, an
  483. ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
  484. This function requires the _imagingft service.
  485. :param font: A filename or file-like object containing a TrueType font.
  486. If the file is not found in this filename, the loader may also
  487. search in other directories, such as the :file:`fonts/`
  488. directory on Windows or :file:`/Library/Fonts/`,
  489. :file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on
  490. macOS.
  491. :param size: The requested size, in points.
  492. :param index: Which font face to load (default is first available face).
  493. :param encoding: Which font encoding to use (default is Unicode). Possible
  494. encodings include (see the FreeType documentation for more
  495. information):
  496. * "unic" (Unicode)
  497. * "symb" (Microsoft Symbol)
  498. * "ADOB" (Adobe Standard)
  499. * "ADBE" (Adobe Expert)
  500. * "ADBC" (Adobe Custom)
  501. * "armn" (Apple Roman)
  502. * "sjis" (Shift JIS)
  503. * "gb " (PRC)
  504. * "big5"
  505. * "wans" (Extended Wansung)
  506. * "joha" (Johab)
  507. * "lat1" (Latin-1)
  508. This specifies the character set to use. It does not alter the
  509. encoding of any text provided in subsequent operations.
  510. :param layout_engine: Which layout engine to use, if available:
  511. `ImageFont.LAYOUT_BASIC` or `ImageFont.LAYOUT_RAQM`.
  512. :return: A font object.
  513. :exception IOError: If the file could not be read.
  514. """
  515. def freetype(font):
  516. return FreeTypeFont(font, size, index, encoding, layout_engine)
  517. try:
  518. return freetype(font)
  519. except IOError:
  520. if not isPath(font):
  521. raise
  522. ttf_filename = os.path.basename(font)
  523. dirs = []
  524. if sys.platform == "win32":
  525. # check the windows font repository
  526. # NOTE: must use uppercase WINDIR, to work around bugs in
  527. # 1.5.2's os.environ.get()
  528. windir = os.environ.get("WINDIR")
  529. if windir:
  530. dirs.append(os.path.join(windir, "fonts"))
  531. elif sys.platform in ("linux", "linux2"):
  532. lindirs = os.environ.get("XDG_DATA_DIRS", "")
  533. if not lindirs:
  534. # According to the freedesktop spec, XDG_DATA_DIRS should
  535. # default to /usr/share
  536. lindirs = "/usr/share"
  537. dirs += [os.path.join(lindir, "fonts") for lindir in lindirs.split(":")]
  538. elif sys.platform == "darwin":
  539. dirs += [
  540. "/Library/Fonts",
  541. "/System/Library/Fonts",
  542. os.path.expanduser("~/Library/Fonts"),
  543. ]
  544. ext = os.path.splitext(ttf_filename)[1]
  545. first_font_with_a_different_extension = None
  546. for directory in dirs:
  547. for walkroot, walkdir, walkfilenames in os.walk(directory):
  548. for walkfilename in walkfilenames:
  549. if ext and walkfilename == ttf_filename:
  550. return freetype(os.path.join(walkroot, walkfilename))
  551. elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
  552. fontpath = os.path.join(walkroot, walkfilename)
  553. if os.path.splitext(fontpath)[1] == ".ttf":
  554. return freetype(fontpath)
  555. if not ext and first_font_with_a_different_extension is None:
  556. first_font_with_a_different_extension = fontpath
  557. if first_font_with_a_different_extension:
  558. return freetype(first_font_with_a_different_extension)
  559. raise
  560. def load_path(filename):
  561. """
  562. Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
  563. bitmap font along the Python path.
  564. :param filename: Name of font file.
  565. :return: A font object.
  566. :exception IOError: If the file could not be read.
  567. """
  568. for directory in sys.path:
  569. if isDirectory(directory):
  570. if not isinstance(filename, str):
  571. if py3:
  572. filename = filename.decode("utf-8")
  573. else:
  574. filename = filename.encode("utf-8")
  575. try:
  576. return load(os.path.join(directory, filename))
  577. except IOError:
  578. pass
  579. raise IOError("cannot find font file")
  580. def load_default():
  581. """Load a "better than nothing" default font.
  582. .. versionadded:: 1.1.4
  583. :return: A font object.
  584. """
  585. from io import BytesIO
  586. import base64
  587. f = ImageFont()
  588. f._load_pilfont_data(
  589. # courB08
  590. BytesIO(
  591. base64.b64decode(
  592. b"""
  593. UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  594. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  595. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  596. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  597. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  598. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  599. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  600. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  601. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  602. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  603. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  604. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA
  605. BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL
  606. AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA
  607. AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
  608. ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
  609. BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
  610. //kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
  611. AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
  612. AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
  613. ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
  614. AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
  615. /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
  616. AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
  617. AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
  618. AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
  619. BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
  620. AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
  621. 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
  622. AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
  623. +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
  624. ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
  625. BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
  626. AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
  627. AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
  628. AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
  629. BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
  630. //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
  631. AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
  632. AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
  633. mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
  634. AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
  635. AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
  636. AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
  637. Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
  638. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  639. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  640. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  641. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  642. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  643. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  644. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  645. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  646. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  647. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  648. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  649. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
  650. //sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
  651. AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
  652. AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
  653. DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
  654. AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
  655. +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
  656. AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
  657. ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
  658. AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
  659. BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
  660. Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
  661. eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
  662. AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
  663. +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
  664. ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
  665. BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
  666. AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
  667. AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
  668. Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
  669. Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
  670. //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
  671. AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
  672. AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
  673. LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
  674. AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
  675. AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
  676. AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
  677. AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
  678. AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
  679. EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
  680. AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
  681. pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
  682. AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
  683. +QAGAAIAzgAKANUAEw==
  684. """
  685. )
  686. ),
  687. Image.open(
  688. BytesIO(
  689. base64.b64decode(
  690. b"""
  691. iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
  692. Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
  693. M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
  694. LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
  695. IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
  696. Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
  697. NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
  698. in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
  699. SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
  700. AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
  701. y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
  702. ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
  703. lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
  704. /Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
  705. AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
  706. c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
  707. /yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
  708. pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
  709. oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
  710. evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
  711. AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
  712. Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
  713. w7IkEbzhVQAAAABJRU5ErkJggg==
  714. """
  715. )
  716. )
  717. ),
  718. )
  719. return f