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
·449 lines (400 loc) · 13.5 KB
/
Copy pathfont2bytes.py
File metadata and controls
executable file
·449 lines (400 loc) · 13.5 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#!/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
import sys
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,
x_offset: int,
y_offset: int,
extend_width: int,
cut_bottom: int = 0,
cut_right: int = 0,
) -> Image.Image:
if variable_width:
width = round(font.getlength(chr(ASCII))) + extend_width
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(
(x_offset, y_offset), chr(ASCII), fill=255, font=font, anchor="la"
)
squeezed_image = temp_image.resize((width, height), Image.Resampling.HAMMING)
image.paste(squeezed_image, (0, 0))
else:
draw.text((x_offset, y_offset), chr(ASCII), fill=255, font=font, anchor="la")
image = image.crop((0, 0, width - cut_right, height - cut_bottom))
return image, width - cut_right
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 encodeRLE(hex_map):
rle = []
if int(hex_map[0], 16) & (1 << 7):
print("Can't RLE encode bin staring with 1")
return None
counting = "0"
cnt = 0
for byte in hex_map:
for i in range(7, 0, -1):
if int(byte, 16) & (1 << i):
if counting != "1":
rle.append(cnt)
cnt = 0
counting = "1"
else:
if counting != "0":
rle.append(cnt)
cnt = 0
counting = "0"
cnt += 1
rle.append(cnt)
# print(rle)
return rle
def write_file_intro(f, ffmt) -> None:
f.write("/* File automatically generated by font2bytes */\n")
f.write(f"/* {' '.join(sys.argv)} */\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[char_list[0]]}, /* 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(
"--extend-width",
type=int,
default=0,
help="Extend width by X pixel, can only be used with --variable-width",
)
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.",
)
parser.add_argument(
"--y-offset",
type=int,
default=0,
help="Y offset when drawing character",
)
parser.add_argument(
"--x-offset",
type=int,
default=0,
help="X offset when drawing character",
)
parser.add_argument(
"--cut-bottom",
type=int,
default=0,
help="cut X pixel on the bottom of each character",
)
parser.add_argument(
"--cut-right",
type=int,
default=0,
help="cut X pixel on the right of each character",
)
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.variable_width is False and args.extend_width != 0:
print("Argument --extend-width can only be used with --variable-width")
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,
args.x_offset,
args.y_offset,
args.extend_width,
args.cut_bottom,
args.cut_right,
)
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 - args.cut_bottom,
char_width,
args.threshold,
binary_map,
)
write_letter(
cfile,
args.format_font,
ASCII,
args.height - args.cut_bottom,
char_width,
hex_map,
)
write_file_closure(
cfile,
args.format_font,
font_name,
args.height - args.cut_bottom,
width_table,
char_list,
)
print()
if __name__ == "__main__":
main()