BdfFontFile.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 typing import BinaryIO
  24. from . import FontFile, Image
  25. bdf_slant = {
  26. "R": "Roman",
  27. "I": "Italic",
  28. "O": "Oblique",
  29. "RI": "Reverse Italic",
  30. "RO": "Reverse Oblique",
  31. "OT": "Other",
  32. }
  33. bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
  34. def bdf_char(
  35. f: BinaryIO,
  36. ) -> (
  37. tuple[
  38. str,
  39. int,
  40. tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
  41. Image.Image,
  42. ]
  43. | None
  44. ):
  45. # skip to STARTCHAR
  46. while True:
  47. s = f.readline()
  48. if not s:
  49. return None
  50. if s[:9] == b"STARTCHAR":
  51. break
  52. id = s[9:].strip().decode("ascii")
  53. # load symbol properties
  54. props = {}
  55. while True:
  56. s = f.readline()
  57. if not s or s[:6] == b"BITMAP":
  58. break
  59. i = s.find(b" ")
  60. props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
  61. # load bitmap
  62. bitmap = bytearray()
  63. while True:
  64. s = f.readline()
  65. if not s or s[:7] == b"ENDCHAR":
  66. break
  67. bitmap += s[:-1]
  68. # The word BBX
  69. # followed by the width in x (BBw), height in y (BBh),
  70. # and x and y displacement (BBxoff0, BByoff0)
  71. # of the lower left corner from the origin of the character.
  72. width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
  73. # The word DWIDTH
  74. # followed by the width in x and y of the character in device pixels.
  75. dwx, dwy = (int(p) for p in props["DWIDTH"].split())
  76. bbox = (
  77. (dwx, dwy),
  78. (x_disp, -y_disp - height, width + x_disp, -y_disp),
  79. (0, 0, width, height),
  80. )
  81. try:
  82. im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
  83. except ValueError:
  84. # deal with zero-width characters
  85. im = Image.new("1", (width, height))
  86. return id, int(props["ENCODING"]), bbox, im
  87. class BdfFontFile(FontFile.FontFile):
  88. """Font file plugin for the X11 BDF format."""
  89. def __init__(self, fp: BinaryIO):
  90. super().__init__()
  91. s = fp.readline()
  92. if s[:13] != b"STARTFONT 2.1":
  93. msg = "not a valid BDF file"
  94. raise SyntaxError(msg)
  95. props = {}
  96. comments = []
  97. while True:
  98. s = fp.readline()
  99. if not s or s[:13] == b"ENDPROPERTIES":
  100. break
  101. i = s.find(b" ")
  102. props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
  103. if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
  104. if s.find(b"LogicalFontDescription") < 0:
  105. comments.append(s[i + 1 : -1].decode("ascii"))
  106. while True:
  107. c = bdf_char(fp)
  108. if not c:
  109. break
  110. id, ch, (xy, dst, src), im = c
  111. if 0 <= ch < len(self.glyph):
  112. self.glyph[ch] = xy, dst, src, im