Root/kernel-6x10/png2font.py

1#!/usr/bin/env python2
2# Converts PNG to Linux font character array.
3
4import sys
5# Python Imaging Library
6# http://www.pythonware.com/products/pil/
7import Image
8
9def getCellSize(image):
10    x, y = image.size
11    width = (x / 32) - 1
12    height = (y / 8) - 1
13    assert 32 * (width + 1) + 1 == x, x
14    assert 8 * (height + 1) + 1 == y, y
15    return width, height
16
17def createData(width, height, image):
18    data = []
19
20    # Scan characters.
21    for c in xrange(256):
22        row, col = divmod(c, 32)
23        y = 1 + row * (height + 1)
24        for i in xrange(height):
25            x = 1 + col * (width + 1)
26            pat = 0
27            mask = 128
28            for bit in xrange(width):
29                if image.getpixel((x, y)):
30                    pat |= mask
31                mask >>= 1
32                x += 1
33            y += 1
34            data.append(pat)
35
36    return data
37
38if len(sys.argv) != 2:
39    print >>sys.stderr, 'Usage: python png2font.py <image_file>'
40    sys.exit(2)
41else:
42    fileName = sys.argv[1]
43    assert fileName.endswith('.png')
44    outFileName = fileName[ : -4] + '.c'
45
46image = Image.open(fileName)
47width, height = getCellSize(image)
48data = createData(width, height, image)
49arrayName = 'fontdata_%dx%d' % (width, height)
50
51out = open(outFileName, 'w')
52try:
53    print >>out, '#include <linux/font.h>'
54    print >>out
55# print >>out, '#define FONTDATAMAX (%d*256)' % height
56# print >>out
57    print >>out, 'static const unsigned char %s[] = {' % arrayName
58    print >>out
59    for c in xrange(256):
60        if c < 32:
61            cs = '^%s' % chr(c + 64)
62        elif c >= 128:
63            cs = '\\%o' % c
64        else:
65            cs = chr(c)
66        print >>out, "\t/* %d 0x%02X '%s' */" % (c, c, cs)
67        for i in xrange(c * height, (c + 1) * height):
68            d = data[i]
69            ds = ''.join(
70                str((d >> bit) & 1)
71                for bit in reversed(xrange(8))
72                )
73            print >>out, '\t0x%02X, /* %s */' % (d, ds)
74        print >>out
75    print >>out, '};'
76    print >>out
77    print >>out, 'const struct font_desc font_%dx%d = {' \
78            % (width, height)
79    print >>out, '\t.idx\t= FONT%dx%d_IDX,' % (width, height)
80    print >>out, '\t.name\t= "%dx%d",' % (width, height)
81    print >>out, '\t.width\t= %d,' % width
82    print >>out, '\t.height\t= %d,' % height
83    print >>out, '\t.data\t= %s,' % arrayName
84    print >>out, '\t.pref\t= 0,'
85    print >>out, '};'
86finally:
87    out.close()
88

Archive Download this file

Branches:
master



interactive