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