You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.7 KiB

4 years ago
  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. from __future__ import print_function
  17. import os
  18. from . import Image, _binary
  19. WIDTH = 800
  20. def puti16(fp, values):
  21. # write network order (big-endian) 16-bit sequence
  22. for v in values:
  23. if v < 0:
  24. v += 65536
  25. fp.write(_binary.o16be(v))
  26. ##
  27. # Base class for raster font file handlers.
  28. class FontFile(object):
  29. bitmap = None
  30. def __init__(self):
  31. self.info = {}
  32. self.glyph = [None] * 256
  33. def __getitem__(self, ix):
  34. return self.glyph[ix]
  35. def compile(self):
  36. "Create metrics and bitmap"
  37. if self.bitmap:
  38. return
  39. # create bitmap large enough to hold all data
  40. h = w = maxwidth = 0
  41. lines = 1
  42. for glyph in self:
  43. if glyph:
  44. d, dst, src, im = glyph
  45. h = max(h, src[3] - src[1])
  46. w = w + (src[2] - src[0])
  47. if w > WIDTH:
  48. lines += 1
  49. w = (src[2] - src[0])
  50. maxwidth = max(maxwidth, w)
  51. xsize = maxwidth
  52. ysize = lines * h
  53. if xsize == 0 and ysize == 0:
  54. return ""
  55. self.ysize = h
  56. # paste glyphs into bitmap
  57. self.bitmap = Image.new("1", (xsize, ysize))
  58. self.metrics = [None] * 256
  59. x = y = 0
  60. for i in range(256):
  61. glyph = self[i]
  62. if glyph:
  63. d, dst, src, im = glyph
  64. xx = src[2] - src[0]
  65. # yy = src[3] - src[1]
  66. x0, y0 = x, y
  67. x = x + xx
  68. if x > WIDTH:
  69. x, y = 0, y + h
  70. x0, y0 = x, y
  71. x = xx
  72. s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
  73. self.bitmap.paste(im.crop(src), s)
  74. self.metrics[i] = d, dst, s
  75. def save(self, filename):
  76. "Save font"
  77. self.compile()
  78. # font data
  79. self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
  80. # font metrics
  81. with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
  82. fp.write(b"PILfont\n")
  83. fp.write((";;;;;;%d;\n" % self.ysize).encode('ascii')) # HACK!!!
  84. fp.write(b"DATA\n")
  85. for id in range(256):
  86. m = self.metrics[id]
  87. if not m:
  88. puti16(fp, [0] * 10)
  89. else:
  90. puti16(fp, m[0] + m[1] + m[2])