Python实现点阵字体读取与转换的方法

时间:2022-12-08 18:33:50

点阵字体是指根据文字的像素点来显示的字体,效果如下:

Python实现点阵字体读取与转换的方法

使用python读取并显示的过程如下:

根据中文字符获取gb2312编码

通过gb2312编码计算该汉字在点阵字库中的区位和码位

通过区位和码位计算在点阵字库中的偏移量

基于偏移量获取该汉字的32个像素存储字节

解析像素字节获取点阵坐标信息

在对应的坐标显示信息位。如该像素点是否显示点亮

使用该代码前提:下载点阵字体库到本地,这里默认使用的是hzk16点阵字库

代码如下:

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

以上这篇python实现点阵字体读取与转换的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/five3/article/details/78229017