build_font_from_bdf.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/env python3
  2. # 导入所需的库
  3. from bdflib import reader
  4. # 读取 BDF 格式的字体文件
  5. font = reader.read_bdf(open("temp/fusion-pixel-12px-monospaced-zh_hans.bdf", "rb"))
  6. # File format version; currently this must be 0.
  7. version = '0'
  8. # 定义字体的高度和宽度
  9. height = 13
  10. width = 12
  11. # 定义垂直偏移量
  12. v_offset = -2
  13. # 初始化计数器
  14. count = 0
  15. print(f'''%PSF2
  16. Version: {version}
  17. Flags: 1
  18. Length: 512
  19. Width: {width}
  20. Height: {height}''', end='')
  21. def PrintNonChineseCharacter(index):
  22. count = index
  23. # 输出空格
  24. PrintCharacters('               ', count)
  25. count += 1
  26. # 打开包含其他字符的参考文件
  27. with open("original/references/other_characters", encoding="utf-8") as f:
  28. for lines in f:
  29. line = lines.split()
  30. PrintCharacters(line[0], count)
  31. count += 1
  32. return count
  33. def PrintCharacters(Characters, count):
  34. Character = Characters[0] # 取第一个字符作为展示字
  35. try:
  36. # 将字符编码为对应编码
  37. encoding = "utf-8"
  38. # _enc = codecs.encode(Character, encoding=encoding)
  39. # 获取对应的字形:即取 ENCODING 变量为字的 Unicode 编码的字形,不同字体中,ENCODING 变量数值的含义可能不同
  40. try:
  41. glyph = font[ord(Character)]
  42. except KeyError:
  43. print(f"警告:字符“{Character}”的 {encoding} 编码:“{ord(Character)}”无法在文件中找到。")
  44. exit(1)
  45. print("\n%")
  46. print("//", count, Character)
  47. # 打印字形的位图表示
  48. print("Bitmap: ", end="")
  49. o_pixels = [[y for y in x] for x in glyph.iter_pixels()]
  50. [left, bottom, w, h] = glyph.get_bounding_box()
  51. # 初始化一个空的像素矩阵
  52. pixels = [["-" for j in range(0, width)] for i in range(0, height)]
  53. # 填充像素矩阵
  54. for i in range(0, h):
  55. for j in range(0, w):
  56. pixels[-bottom - h + i + v_offset][left + j] = ("#" if o_pixels[i][j] else "-")
  57. # 打印像素矩阵
  58. for l in range(0, height):
  59. ll = "".join(pixels[l])
  60. if l < height - 1:
  61. ll = ll + " \\"
  62. print(ll)
  63. # 打印字符的 Unicode 编码
  64. print("Unicode: ", end="")
  65. for h in Characters:
  66. # 遇到 # 则停止
  67. if h == "#":
  68. break
  69. print("[{0:08x}];".format(ord(h)), end="")
  70. except UnicodeError:
  71. # 捕获并处理 Unicode 错误
  72. pass
  73. # 打开包含拼音和对应汉字的参考文件
  74. with open("original/references/pinyin_hanzi", encoding="utf-8") as f:
  75. count = 0
  76. for line in f:
  77. if count == 32:
  78. count = PrintNonChineseCharacter(count)
  79. # 跳过注释行
  80. if line.startswith("#"):
  81. continue
  82. s = line.split() # 分开拼音和汉字
  83. if len(s) >= 2:
  84. hanzis = s[1] # 取汉字那一条
  85. PrintCharacters(hanzis, count)
  86. count += 1