Root/
1 | #!/usr/bin/env python2 |
2 | # Converts Linux font character array to PNG. |
3 | |
4 | import sys |
5 | # Python Imaging Library |
6 | # http://www.pythonware.com/products/pil/ |
7 | import Image |
8 | |
9 | def readSource(inp): |
10 | data = [] |
11 | meta = {} |
12 | inData = False |
13 | inMeta = False |
14 | for line in inp.readlines(): |
15 | csta = line.find('/*') |
16 | if csta != -1: |
17 | cend = line.index('*/') + 2 |
18 | line = line[ : csta] + line[cend : ] |
19 | line = line.strip() |
20 | if inData: |
21 | if line == '};': |
22 | inData = False |
23 | elif line: |
24 | valStr = line.rstrip(',') |
25 | # Chars wider than 8 not supported yet. |
26 | assert ',' not in valStr |
27 | data.append(int(valStr, 16)) |
28 | elif inMeta: |
29 | if line == '};': |
30 | inMeta = False |
31 | elif line: |
32 | key, value = line.split('=') |
33 | key = key.strip().lstrip('.') |
34 | value = value.strip().rstrip(',') |
35 | meta[key] = value |
36 | elif line.startswith('static const unsigned char'): |
37 | assert line[-1] == '{' |
38 | inData = True |
39 | elif line.startswith('const struct font_desc'): |
40 | assert line[-1] == '{' |
41 | inMeta = True |
42 | return data, meta |
43 | |
44 | def createImage(width, height, data): |
45 | assert len(data) == height * 256 |
46 | |
47 | # Reserve space for a 32 * 8 grid of characters. |
48 | image = Image.new('P', (32 * (width + 1) + 1, 8 * (height + 1) + 1)) |
49 | palette = [0, 0, 0] * 256 |
50 | palette[3 : 6] = [255, 255, 255] # foreground |
51 | palette[6 : 9] = [128, 0, 0] # grid |
52 | image.putpalette(palette) |
53 | |
54 | # Draw grid. |
55 | for y in xrange(0, image.size[1], height + 1): |
56 | for x in xrange(0, image.size[0]): |
57 | image.putpixel((x, y), 2) |
58 | for x in xrange(0, image.size[0], width + 1): |
59 | for y in xrange(0, image.size[1]): |
60 | image.putpixel((x, y), 2) |
61 | |
62 | # Draw characters. |
63 | for c in xrange(256): |
64 | row, col = divmod(c, 32) |
65 | y = 1 + row * (height + 1) |
66 | for i in xrange(c * height, (c + 1) * height): |
67 | x = 1 + col * (width + 1) |
68 | pat = data[i] |
69 | for bit in xrange(width): |
70 | if pat & 128: |
71 | image.putpixel((x, y), 1) |
72 | pat <<= 1 |
73 | x += 1 |
74 | y += 1 |
75 | return image |
76 | |
77 | if len(sys.argv) != 2: |
78 | print >>sys.stderr, 'Usage: python font2png.py <source_file>' |
79 | sys.exit(2) |
80 | else: |
81 | fileName = sys.argv[1] |
82 | assert fileName.endswith('.c') |
83 | outFileName = fileName[ : -2] + '.png' |
84 | |
85 | inp = open(fileName, 'r') |
86 | try: |
87 | data, meta = readSource(inp) |
88 | finally: |
89 | inp.close() |
90 | width = int(meta['width']) |
91 | height = int(meta['height']) |
92 | image = createImage(width, height, data) |
93 | image.save(outFileName) |
94 |
Branches:
master