FontFile.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # base class for raster font file parsers
  6. #
  7. # history:
  8. # 1997-06-05 fl created
  9. # 1997-08-19 fl restrict image width
  10. #
  11. # Copyright (c) 1997-1998 by Secret Labs AB
  12. # Copyright (c) 1997-1998 by Fredrik Lundh
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. import os
  17. from . import Image, _binary
  18. WIDTH = 800
  19. def puti16(fp, values):
  20. """Write network order (big-endian) 16-bit sequence"""
  21. for v in values:
  22. if v < 0:
  23. v += 65536
  24. fp.write(_binary.o16be(v))
  25. class FontFile:
  26. """Base class for raster font file handlers."""
  27. bitmap = None
  28. def __init__(self):
  29. self.info = {}
  30. self.glyph = [None] * 256
  31. def __getitem__(self, ix):
  32. return self.glyph[ix]
  33. def compile(self):
  34. """Create metrics and bitmap"""
  35. if self.bitmap:
  36. return
  37. # create bitmap large enough to hold all data
  38. h = w = maxwidth = 0
  39. lines = 1
  40. for glyph in self:
  41. if glyph:
  42. d, dst, src, im = glyph
  43. h = max(h, src[3] - src[1])
  44. w = w + (src[2] - src[0])
  45. if w > WIDTH:
  46. lines += 1
  47. w = src[2] - src[0]
  48. maxwidth = max(maxwidth, w)
  49. xsize = maxwidth
  50. ysize = lines * h
  51. if xsize == 0 and ysize == 0:
  52. return ""
  53. self.ysize = h
  54. # paste glyphs into bitmap
  55. self.bitmap = Image.new("1", (xsize, ysize))
  56. self.metrics = [None] * 256
  57. x = y = 0
  58. for i in range(256):
  59. glyph = self[i]
  60. if glyph:
  61. d, dst, src, im = glyph
  62. xx = src[2] - src[0]
  63. # yy = src[3] - src[1]
  64. x0, y0 = x, y
  65. x = x + xx
  66. if x > WIDTH:
  67. x, y = 0, y + h
  68. x0, y0 = x, y
  69. x = xx
  70. s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
  71. self.bitmap.paste(im.crop(src), s)
  72. self.metrics[i] = d, dst, s
  73. def save(self, filename):
  74. """Save font"""
  75. self.compile()
  76. # font data
  77. self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
  78. # font metrics
  79. with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
  80. fp.write(b"PILfont\n")
  81. fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
  82. fp.write(b"DATA\n")
  83. for id in range(256):
  84. m = self.metrics[id]
  85. if not m:
  86. puti16(fp, [0] * 10)
  87. else:
  88. puti16(fp, m[0] + m[1] + m[2])