Root/
| 1 | #!/usr/bin/env python2 |
| 2 | # Converts PNG to Linux font character array. |
| 3 | |
| 4 | import sys |
| 5 | # Python Imaging Library |
| 6 | # http://www.pythonware.com/products/pil/ |
| 7 | import Image |
| 8 | |
| 9 | def 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 | |
| 17 | def 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 | |
| 38 | if len(sys.argv) != 2: |
| 39 | print >>sys.stderr, 'Usage: python png2font.py <image_file>' |
| 40 | sys.exit(2) |
| 41 | else: |
| 42 | fileName = sys.argv[1] |
| 43 | assert fileName.endswith('.png') |
| 44 | outFileName = fileName[ : -4] + '.c' |
| 45 | |
| 46 | image = Image.open(fileName) |
| 47 | width, height = getCellSize(image) |
| 48 | data = createData(width, height, image) |
| 49 | arrayName = 'fontdata_%dx%d' % (width, height) |
| 50 | |
| 51 | out = open(outFileName, 'w') |
| 52 | try: |
| 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, '};' |
| 86 | finally: |
| 87 | out.close() |
| 88 |
Branches:
master
