build_font_from_bdf.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #!/usr/bin/env python3
  2. # 导入所需的库
  3. from bdflib import reader
  4. # 读取 BDF 格式的字体文件
  5. font = reader.read_bdf(open("temp/wqy-bitmapsong/wenquanyi_9pt.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():
  22. # 输出空格
  23. PrintCharacters('               ')
  24. # 打开包含其他字符的参考文件
  25. with open("original/references/other_characters", encoding="utf-8") as f:
  26. for lines in f:
  27. line = lines.split()
  28. PrintCharacters(line[0])
  29. def PrintCharacters(Characters):
  30. global count
  31. Character = Characters[0]
  32. try:
  33. # 将汉字编码为对应编码
  34. encoding = "utf-8"
  35. # _enc = codecs.encode(Character, encoding=encoding)
  36. # 获取对应的字形:即取 ENCODING 变量为字的 Unicode 编码的字形,不同字体中,ENCODING 变量数值的含义可能不同
  37. try:
  38. glyph = font[ord(Character)]
  39. except KeyError:
  40. print(f"警告:字符“{Character}”的 {encoding} 编码:“{ord(Character)}”无法在文件中找到。")
  41. exit(1)
  42. print("\n%")
  43. print("//", count, Character)
  44. count += 1
  45. # 打印字形的位图表示
  46. print("Bitmap: ", end="")
  47. o_pixels = [[y for y in x] for x in glyph.iter_pixels()]
  48. [left, bottom, w, h] = glyph.get_bounding_box()
  49. # 初始化一个空的像素矩阵
  50. pixels = [["-" for j in range(0, width)] for i in range(0, height)]
  51. # 填充像素矩阵
  52. for i in range(0, h):
  53. for j in range(0, w):
  54. pixels[-bottom - h + i + v_offset][left + j] = ("#" if o_pixels[i][j] else "-")
  55. # 打印像素矩阵
  56. for l in range(0, height):
  57. ll = "".join(pixels[l])
  58. if l < height - 1:
  59. ll = ll + " \\"
  60. print(ll)
  61. # 打印汉字的 Unicode 编码
  62. print("Unicode: ", end="")
  63. for h in Characters:
  64. # 遇到 # 则停止
  65. if h == "#":
  66. break
  67. print("[{0:08x}];".format(ord(h)), end="")
  68. if count == 32:
  69. PrintNonChineseCharacter()
  70. except UnicodeError:
  71. # 捕获并处理 Unicode 错误
  72. pass
  73. # 打开包含拼音和对应汉字的参考文件
  74. with open("original/references/pinyin_hanzi", encoding="utf-8") as f:
  75. for line in f:
  76. # 跳过注释行
  77. if line.startswith("#"):
  78. continue
  79. s = line.split()
  80. if len(s) >= 2:
  81. hanzis = s[1]
  82. PrintCharacters(hanzis)