BdfFontFile.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # bitmap distribution font (bdf) file parser
  6. #
  7. # history:
  8. # 1996-05-16 fl created (as bdf2pil)
  9. # 1997-08-25 fl converted to FontFile driver
  10. # 2001-05-25 fl removed bogus __init__ call
  11. # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
  12. # 2003-04-22 fl more robustification (from Graham Dumpleton)
  13. #
  14. # Copyright (c) 1997-2003 by Secret Labs AB.
  15. # Copyright (c) 1997-2003 by Fredrik Lundh.
  16. #
  17. # See the README file for information on usage and redistribution.
  18. #
  19. """
  20. Parse X Bitmap Distribution Format (BDF)
  21. """
  22. from __future__ import annotations
  23. from . import FontFile, Image
  24. TYPE_CHECKING = False
  25. if TYPE_CHECKING:
  26. from typing import BinaryIO
  27. def bdf_char(
  28. f: BinaryIO,
  29. ) -> (
  30. tuple[
  31. str,
  32. int,
  33. tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
  34. Image.Image,
  35. ]
  36. | None
  37. ):
  38. # skip to STARTCHAR
  39. while True:
  40. s = f.readline()
  41. if not s:
  42. return None
  43. if s.startswith(b"STARTCHAR"):
  44. break
  45. id = s[9:].strip().decode("ascii")
  46. # load symbol properties
  47. props = {}
  48. while True:
  49. s = f.readline()
  50. if not s or s.startswith(b"BITMAP"):
  51. break
  52. i = s.find(b" ")
  53. props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
  54. # load bitmap
  55. bitmap = bytearray()
  56. while True:
  57. s = f.readline()
  58. if not s or s.startswith(b"ENDCHAR"):
  59. break
  60. bitmap += s[:-1]
  61. # The word BBX
  62. # followed by the width in x (BBw), height in y (BBh),
  63. # and x and y displacement (BBxoff0, BByoff0)
  64. # of the lower left corner from the origin of the character.
  65. width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
  66. Image._decompression_bomb_check((width, height))
  67. # The word DWIDTH
  68. # followed by the width in x and y of the character in device pixels.
  69. dwx, dwy = (int(p) for p in props["DWIDTH"].split())
  70. bbox = (
  71. (dwx, dwy),
  72. (x_disp, -y_disp - height, width + x_disp, -y_disp),
  73. (0, 0, width, height),
  74. )
  75. im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
  76. return id, int(props["ENCODING"]), bbox, im
  77. class BdfFontFile(FontFile.FontFile):
  78. """Font file plugin for the X11 BDF format."""
  79. def __init__(self, fp: BinaryIO) -> None:
  80. super().__init__()
  81. s = fp.readline()
  82. if not s.startswith(b"STARTFONT 2.1"):
  83. msg = "not a valid BDF file"
  84. raise SyntaxError(msg)
  85. props = {}
  86. comments = []
  87. while True:
  88. s = fp.readline()
  89. if not s or s.startswith(b"ENDPROPERTIES"):
  90. break
  91. i = s.find(b" ")
  92. props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
  93. if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
  94. if s.find(b"LogicalFontDescription") < 0:
  95. comments.append(s[i + 1 : -1].decode("ascii"))
  96. while True:
  97. c = bdf_char(fp)
  98. if not c:
  99. break
  100. id, ch, (xy, dst, src), im = c
  101. if 0 <= ch < len(self.glyph):
  102. self.glyph[ch] = xy, dst, src, im