Debian Codegraph @

graphics/text/smtextgen

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: BSD-3-Clause
3 #
4 # Script to generate text graphics using the "small" (HUD) font.
5 #
6
7 from PIL import Image
8 from glob import glob
9 import sys
10 import re
11
12 from image_dimensions import *
13 from tint import image_tint
14
15 DIMENSION_MATCH_RE = re.compile(r"(\d+)[x,](\d+)")
16
17
18 class SmallTextGenerator(object):
19 def __init__(self):
20 self.get_font_widths()
21
22 # Width of a space character in pixels.
23 SPACE_WIDTH = 4
24 # Height of the font.
25 FONT_HEIGHT = 8
26 # Regexp to match dimensions/x,y coordinate pair.
27
28 def compile_kerning_table(self, kerning_table):
29 """Given a dictionary of kerning patterns, compile Regexps."""
30
31 result = {}
32 for pattern, adjust in kerning_table.items():
33 result[re.compile(pattern)] = adjust
34 return result
35
36 def get_font_widths(self):
37 charfiles = glob("../stcfn*.png")
38 self.char_widths = {}
39 for c in range(128):
40 filename = self.char_filename(chr(c))
41 if filename not in charfiles:
42 continue
43 w, _ = get_image_dimensions(filename)
44 self.char_widths[chr(c)] = w
45
46 def __contains__(self, c):
47 return c in self.char_widths
48
49 def char_width(self, c):
50 return self.char_widths[c]
51
52 def char_filename(self, c):
53 return "../stcfn%03d.png" % (ord(c))
54
55 def draw_for_text(self, image, text, x, y):
56 text = text.upper()
57 new_image = image.copy()
58 x1, y1 = x, y
59
60 for c in text:
61 if c == "\n":
62 y1 += self.FONT_HEIGHT
63 x1 = x
64 elif c == " ":
65 x1 += self.SPACE_WIDTH
66
67 if c not in self:
68 continue
69
70 filename = self.char_filename(c)
71 char_image = Image.open(filename)
72 char_image.load()
73 new_image = self.paste_image(new_image, char_image, x1, y1)
74 x1 += self.char_width(c)
75 return new_image
76
77 def paste_image(self, image, src, x, y):
78 int_image = Image.new("RGBA", image.size, (0, 0, 0, 0))
79 int_image.paste(src, (x, y))
80 new_image = Image.alpha_composite(image, int_image)
81 return new_image
82
83
84 def parse_command_line(args):
85 if len(args) < 4 or (len(args) % 2) != 0:
86 return None
87
88 result = {"filename": args[0], "background": None, "strings": []}
89
90 m = DIMENSION_MATCH_RE.match(args[1])
91 if not m:
92 return None
93 result["dimensions"] = (int(m.group(1)), int(m.group(2)))
94
95 i = 2
96 while i < len(args):
97 if args[i] == "-background":
98 result["background"] = args[i + 1]
99 i += 2
100 continue
101
102 m = DIMENSION_MATCH_RE.match(args[i])
103 if not m:
104 return None
105
106 xy = (int(m.group(1)), int(m.group(2)))
107
108 result["strings"].append((xy, args[i + 1]))
109 i += 2
110
111 return result
112
113
114 if __name__ == "__main__":
115
116 args = parse_command_line(sys.argv[1:])
117
118 if not args:
119 print("Usage: smtextgen <filename> <size> [...text commands...]")
120 print("Where each text command looks like:")
121 print(" [x,y] [text]")
122 sys.exit(0)
123
124 smallfont = SmallTextGenerator()
125
126 if args["background"] is not None:
127 background_image = Image.open(args["background"])
128 background_image.load()
129 background_image = background_image.convert("RGBA")
130
131 image = Image.new("RGBA", args["dimensions"], (0, 0, 0, 0))
132
133 for xy, string in args["strings"]:
134 # Allow contents of a file to be included with special prefix:
135 if string.startswith("include:"):
136 with open(string[8:]) as f:
137 string = f.read()
138
139 # Allow special notation to indicate an image file to just draw
140 # rather than rendering a string.
141 if string.startswith("file:"):
142 src_image = Image.open(string[5:])
143 src_image.load()
144 image = smallfont.paste_image(image, src_image, xy[0], xy[1])
145 else:
146 image = smallfont.draw_for_text(image, string, xy[0], xy[1])
147
148 if args["background"] is not None:
149 image = Image.alpha_composite(background_image, image)
150
151 image.save(args["filename"])