forked from theHEXstyle/font2bytes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfont2bytes.py
More file actions
executable file
·353 lines (311 loc) · 11.1 KB
/
font2bytes.py
File metadata and controls
executable file
·353 lines (311 loc) · 11.1 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/usr/bin/env python3
# ==========================================================================
# Copyright (c) theHEXstyle, 2023-2024
# Copyright (c) jfgd, 2026
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <https://www.gnu.org/licenses/>.
# ==========================================================================
import argparse
import re
from pathlib import Path
from PIL import ImageDraw, ImageFont, Image
from numpy import asarray, ceil, array, sum, concatenate
def createTMPimage(
font: ImageFont.FreeTypeFont,
height: int,
width: int,
ASCII: int,
variable_width: bool,
max_width: int,
) -> Image.Image:
if variable_width:
width = round(font.getlength(chr(ASCII)))
if max_width:
width = min(width, max_width)
image = Image.new("L", (width, height), color=(0))
draw = ImageDraw.Draw(image)
if font.getlength(chr(ASCII)) > width:
temp_image = Image.new(
"L", (int(font.getlength(chr(ASCII))), height), color=(0)
)
temp_draw = ImageDraw.Draw(temp_image)
temp_draw.text((0, 0), chr(ASCII), fill=255, font=font)
squeezed_image = temp_image.resize((width, height), Image.Resampling.HAMMING)
image.paste(squeezed_image, (0, 0))
else:
draw.text((0, 0), chr(ASCII), fill=255, font=font)
return image, width
def readImage2Binary(image: Image.Image, ASCII: int):
return asarray(image)
def convertMap2Hex(height: int, width: int, threshold: int, binary_map) -> list:
hex_map = []
binary_byte = array([128, 64, 32, 16, 8, 4, 2, 1])
for line in range(binary_map.shape[0]):
for bit_chunks in range(int(ceil(width / 8))):
tmp = binary_map[line][bit_chunks * 8 : (min((bit_chunks + 1) * 8, width))]
tmp = array(list(map(lambda x: int(x > threshold), tmp)))
tmp = concatenate((tmp, array([0] * (8 - len(tmp))))) # padding with zeros
binary_value = int(sum(tmp * binary_byte))
hex_map.append(f"{binary_value:#0{4}x}")
return hex_map
def write_file_intro(f, ffmt) -> None:
f.write("/* File automatically generated by font2bytes */\n\n")
if ffmt == "jFont":
f.write('#include "jfonts.h"\n\n')
else:
f.write('#include "fonts.h"\n\n')
f.write("static const uint8_t Font_Table [] = \n")
f.write("{\n")
def write_file_closure(
f, ffmt, font_name: str, height: int, width_table: dict, char_list: list
):
if ffmt == "jFont":
f.write(f"jFont {font_name} = {{\n")
f.write(f"\t.max_width = {max(width_table.values())}, /* Maximum width */\n")
f.write(f"\t.height = {height}, /* Height */\n")
f.write(
f"\t.default_char = {char_list[0]}, /* Default: '{chr(char_list[0])}' */\n"
)
f.write(f"\t.min_char = {min(char_list)}, /* Min: '{chr(min(char_list))}' */\n")
f.write(f"\t.max_char = {max(char_list)}, /* Max: '{chr(max(char_list))}' */\n")
f.write(f"\t.nb_glyphs = {len(char_list)},\n")
f.write("\t.glyphs = {\n")
for c in char_list:
f.write("\t\t{\n")
f.write(f"\t\t\t.c = {c}, /* '{chr(c)}' */\n")
f.write(f"\t\t\t.width = {width_table[c]},\n")
f.write(f"\t\t\t.table = fontTable{c},\n")
f.write("\t\t},\n")
f.write("\t}\n")
f.write("};\n\n")
else:
f.write("};\n\n")
f.write(f"sFONT {font_name} = {{\n")
f.write("\tFont_Table,\n")
f.write(f"\t{width_table[c]}, /* Width */\n")
f.write(f"\t{height}, /* Height */\n")
f.write("};\n\n")
def write_letter(f, ffmt, char, height, width, hex_map):
if ffmt == "jFont":
f.write(f"static const uint8_t fontTable{char}[] = \n")
f.write("{\n")
f.write(f'\t/* ASCII: {char} "{chr(char)}" ({width} pixels wide) */\n')
count = 0
f.write("\t")
for item in hex_map:
f.write(f"{item}, ")
count += 1
if count == 3:
count = 0
f.write("\n\t")
if ffmt == "jFont":
f.write("\n};\n\n")
else:
f.write("\n")
def main():
parser = argparse.ArgumentParser(
prog="font2bytes",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Generate C font files for e-Paper "
"(WaveShare like) from .ttf files",
)
parser.add_argument(
"-t",
"--ttf-input-file",
type=Path,
default="./fonts/Roboto-Regular.ttf",
help="A .ttf font file",
)
group_out = parser.add_mutually_exclusive_group()
group_out.add_argument(
"-o",
"--output-file",
type=Path,
help="C output filename",
)
group_out.add_argument(
"-d",
"--output-dir",
type=Path,
default="./output/",
help="C output directory. Use --font-name as file name or guess it.",
)
parser.add_argument(
"-n",
"--font-name",
type=str,
help="Name of the sFONT object in the C file. "
"If unspecified derive it form input file name.",
)
parser.add_argument(
"--format-font",
"-f",
type=str,
choices=["sFONT", "jFont"],
default="sFONT",
help="Output format font, sFONT ou jFont",
)
parser.add_argument(
"--height", type=int, default=36, help="Height of the generated font in pixel"
)
group_width = parser.add_mutually_exclusive_group()
group_width.add_argument(
"--width",
type=int,
help="Width of the generated font in pixel. Defaults to 3/5 of --height.",
)
group_width.add_argument(
"--max-width",
type=int,
help="Maximum width of the generated font in pixel. "
"Defaults to 3/5 of --height.",
)
group_width.add_argument(
"--variable-width",
action="store_true",
default=False,
help="Character width is variable",
)
parser.add_argument(
"-s",
"--ascii-start",
type=int,
default=32,
help="Decimal ASCII value (included) from which to start generating character",
)
group_range = parser.add_mutually_exclusive_group()
group_range.add_argument(
"-e",
"--ascii-end",
type=int,
default=126,
help="Decimal ASCII value (included) at which characters stop being generated",
)
group_range.add_argument(
"-r",
"--ascii-range",
type=str,
help="Comma separate list of ascii number to generate",
)
parser.add_argument(
"--threshold",
type=int,
default=120,
help="Image intensity threshold for binary conversion. "
"It changes the contrast of the final font.",
)
parser.add_argument(
"--font-offset",
type=int,
default=4,
help="Font offset, recommended to be at least 4.",
)
parser.add_argument(
"-b",
"--bmp-dir",
type=Path,
help="Folder to save BMP intermediate image, if unspecified "
"BMP image are not saved. Useful for debugging.",
)
args = parser.parse_args()
if not args.ttf_input_file.is_file():
print(f"File '{args.ttf_input_file}' can not be read")
exit(1)
if args.bmp_dir is not None:
if not args.bmp_dir.is_dir():
print(f"Directory '{args.bmp_dir}' does not exist")
exit(1)
if args.output_dir is not None:
if not args.output_dir.is_dir():
print(f"Directory '{args.output_dir}' does not exist")
exit(1)
if args.ascii_range is not None and args.format_font != "jFont":
print("Argument --ascii-range only valid with 'jFont' format")
exit(1)
if args.max_width is not None and args.format_font != "jFont":
print("Argument --max-width only valid with 'jFont' format")
exit(1)
if args.variable_width is not False and args.format_font != "jFont":
print("Argument --variable-width only valid with 'jFont' format")
exit(1)
if args.font_name is None:
font_name = "Font" + args.ttf_input_file.stem
for i in [" ", "-"]:
font_name = font_name.replace(i, "")
font_name += f"{args.height}"
else:
font_name = args.font_name
if args.output_file is not None:
output_file = args.output_file
else:
output_file = args.output_dir / f"{font_name}.c"
if args.width is None:
width = round((args.height * 3) / 5)
else:
width = args.width
if args.ascii_end < args.ascii_start:
print(
f"ASCII end value ({args.ascii_end}) must be bigger "
f"than ASCII start value ({args.ascii_start})"
)
exit(1)
ranges = [[args.ascii_start, args.ascii_end]]
if args.ascii_range is not None:
args.ascii_range = [s.strip() for s in args.ascii_range.split(",")]
ranges = []
for r in args.ascii_range:
x = re.findall(r"\d+", str(r))
if len(x) == 1:
ranges.append([int(x[0]), int(x[0])])
elif len(x) == 2:
ranges.append([int(x[0]), int(x[1])])
else:
print(f"Range '{r}' not understood")
exit(1)
char_list = []
for r in ranges:
for c in range(r[0], r[1] + 1):
char_list.append(c)
char_list.sort()
print(
f"Generating font '{font_name}' in {output_file} from TTF file {args.ttf_input_file}"
)
with open(output_file, "w") as cfile:
font = ImageFont.truetype(args.ttf_input_file, args.height - args.font_offset)
write_file_intro(cfile, args.format_font)
width_table = {}
print("Generating: ", end="")
for r in ranges:
for ASCII in range(r[0], r[1] + 1):
print(f"{chr(ASCII)}({ASCII}) ", end="")
image, char_width = createTMPimage(
font, args.height, width, ASCII, args.variable_width, args.max_width
)
width_table[ASCII] = char_width
if args.bmp_dir is not None:
image.save(args.bmp_dir / f"{ASCII}.bmp")
binary_map = readImage2Binary(image, ASCII)
hex_map = convertMap2Hex(
args.height, char_width, args.threshold, binary_map
)
write_letter(
cfile, args.format_font, ASCII, args.height, char_width, hex_map
)
write_file_closure(
cfile, args.format_font, font_name, args.height, width_table, char_list
)
print()
if __name__ == "__main__":
main()