70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
import numpy as np
|
|
import PIL.ImageFont as pilfont
|
|
import PIL.Image as pilimage
|
|
import PIL.ImageDraw as pildraw
|
|
|
|
|
|
def generate_chinese_struct(char_code, font):
|
|
image = pilimage.new('L', (16, 16))
|
|
draw = pildraw.Draw(image)
|
|
draw.text((0, 0), char_code, font=font, fill=255)
|
|
pixel_array = np.array(image)
|
|
result = np.zeros(32, dtype=np.uint8)
|
|
for i in range(16):
|
|
for j in range(2):
|
|
for k in range(8):
|
|
if pixel_array[j * 8 + k, i]:
|
|
result[j * 16 + i] |= (1 << k)
|
|
return result
|
|
|
|
|
|
def generate_chinese_array(input_str, font_str):
|
|
font = pilfont.truetype(font_str, size=16)
|
|
chinese_array = []
|
|
for char_code in input_str:
|
|
char_struct = generate_chinese_struct(char_code, font)
|
|
chinese_array.append({'name': char_code, 'data': char_struct})
|
|
return chinese_array
|
|
|
|
|
|
def format_chinese_array_as_text(chinese_array):
|
|
text_output = "Chinese_t Hzk[] = {\n"
|
|
for item in chinese_array:
|
|
unicode_hex = ', '.join(f"0x{ord(char) >> 8:02X}, 0x{ord(char) & 0xFF:02X}" for char in item['name'])
|
|
text_output += f" {{\n // Original: {item['name']}\n"
|
|
text_output += f" {{ {unicode_hex} }},\n {{"
|
|
bytes_str = ', '.join(f"0x{byte:02X}" for byte in item['data'])
|
|
bytes_lines = [bytes_str[i:i + 24 * 4] for i in range(0, len(bytes_str), 24 * 4)] # 每行显示16个数组
|
|
text_output += '\n '.join(bytes_lines)
|
|
text_output += "\n }},\n"
|
|
text_output += "};"
|
|
return text_output
|
|
|
|
|
|
def generate_and_write_chinese_array_output():
|
|
# 生成包含汉字结构体的数组
|
|
# simsun: 宋体
|
|
# kaiti: 楷体
|
|
chinese_array = generate_chinese_array("字库生成测试", 'simsun')
|
|
|
|
# 将数组格式化为文本输出并写入文件
|
|
text_output = format_chinese_array_as_text(chinese_array)
|
|
with open('chinese_array_output.txt', 'w') as file:
|
|
file.write(text_output)
|
|
|
|
|
|
# 调用函数生成并写入汉字数组输出文件
|
|
generate_and_write_chinese_array_output()
|
|
|
|
|
|
def generate_unicode_bin_file():
|
|
font = pilfont.truetype('simsun', size=16)
|
|
with open('cao.bin', 'wb') as file:
|
|
for char_code in range(0x4e00, 0xa000):
|
|
result = generate_chinese_struct(chr(char_code), font)
|
|
file.write(result)
|
|
file.close()
|
|
|
|
# 调用函数生成Unicode二进制文件
|
|
# generate_unicode_bin_file()
|