charpoint.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # !/usr/bin/python
  2. # encoding: utf-8
  3. import binascii
  4. RECT_HEIGHT = 16
  5. RECT_WIDTH = 16
  6. BYTE_COUNT_PER_ROW = RECT_WIDTH / 8
  7. BYTE_COUNT_PER_FONT = BYTE_COUNT_PER_ROW * RECT_HEIGHT
  8. KEYS = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]
  9. class FontRender(object):
  10. def __init__(self, font_file,
  11. rect_height=RECT_HEIGHT, rect_width=RECT_WIDTH, byte_count_per_row=BYTE_COUNT_PER_ROW):
  12. self.font_file = font_file
  13. self.rect_height = rect_height
  14. self.rect_width = rect_width
  15. self.byte_count_per_row = byte_count_per_row
  16. self.__init_rect_list__()
  17. def __init_rect_list__(self):
  18. self.rect_list = [] * RECT_HEIGHT
  19. for i in range(RECT_HEIGHT):
  20. self.rect_list.append([] * RECT_WIDTH)
  21. def get_font_area_index(self, txt, encoding='utf-8'):
  22. if not isinstance(txt, str):
  23. txt = txt.decode(encoding)
  24. gb2312 = txt.encode('gb2312')
  25. hex_str = binascii.b2a_hex(gb2312)
  26. area = eval('0x' + hex_str[:2]) - 0xA0
  27. index = eval('0x' + hex_str[2:]) - 0xA0
  28. return area, index
  29. def get_font_rect(self, area, index):
  30. offset = (94 * (area - 1) + (index - 1)) * BYTE_COUNT_PER_FONT
  31. btxt = None
  32. with open(self.font_file, "rb") as f:
  33. f.seek(offset)
  34. btxt = f.read(BYTE_COUNT_PER_FONT)
  35. return btxt
  36. def convert_font_rect(self, font_rect, ft=1, ff=0):
  37. for k in range(len(font_rect) / self.byte_count_per_row):
  38. row_list = self.rect_list[k]
  39. for j in range(self.byte_count_per_row):
  40. for i in range(8):
  41. asc = binascii.b2a_hex(font_rect[k * self.byte_count_per_row + j])
  42. asc = eval('0x' + asc)
  43. flag = asc & KEYS[i]
  44. row_list.append(flag and ft or ff)
  45. def render_font_rect(self, rect_list=None):
  46. if not rect_list:
  47. rect_list = self.rect_list
  48. for row in rect_list:
  49. for i in row:
  50. if i:
  51. print
  52. '■',
  53. else:
  54. print
  55. '○',
  56. print
  57. def convert(self, text, ft=None, ff=None, encoding='utf-8'):
  58. if not isinstance(text, unicode):
  59. text = text.decode(encoding)
  60. for t in text:
  61. area, index = self.get_font_area_index(t)
  62. font_rect = self.get_font_rect(area, index)
  63. self.convert_font_rect(font_rect, ft=ft, ff=ff)
  64. def get_rect_info(self):
  65. return self.rect_list
  66. if '__main__' == __name__:
  67. text = u'同创伟业'
  68. fr = FontRender('./font/16x16/hzk16h')
  69. fr.convert(text, ft='/static/*', ff=0)
  70. # print fr.get_rect_info()
  71. fr.render_font_rect()