[Horus] font fixes (#5901)
[opentx.git] / radio / util / font2png.py
blob86d0f9c404c04b768fc2dc5cd902a4432c20771f
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 import sys, os
5 import glob
7 from PIL import Image, ImageDraw, ImageFont
9 chars_en = u""" !"#$%&'()*+,-./0123456789:;<=>?°ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz~|≥"""
10 chars_fr = u"""éèàîç"""
11 chars_de = u"""ÄäÖöÜüß"""
12 chars_cz = u"""ěščřžýáíéňóůúďťĚŠČŘŽÝÁÍÉŇÓÚŮĎŤ"""
13 chars_es = u"""Ññ"""
14 chars_fi = u"""åäöÅÄÖ"""
15 chars_it = u"""àù"""
16 chars_pl = u"""ąćęłńóśżźĄĆĘŁŃÓŚŻŹ"""
17 chars_pt = u"""ÁáÂâÃãÀàÇçÉéÊêÍíÓóÔôÕõÚú"""
18 chars_se = u"""åäöÅÄÖ"""
20 COUNT_EXTRA_CHARS = 21
22 chars_extra = u"".join([chr(1+i) for i in range(COUNT_EXTRA_CHARS)])
23 chars = chars_en + chars_extra + chars_fr + chars_de + chars_cz + chars_es + chars_fi + chars_it + chars_pl + chars_se
26 def createFontBitmap(filename, fontname, fontsize, fontoffset, foreground, background, coordsfile=True):
29 coords = []
30 font_filename = 'fonts/' + fontname + '.ttf'
32 print 'Font filename: %s' % font_filename
33 font = ImageFont.truetype(font_filename, fontsize)
35 extraImage = None
36 extraFilename = 'fonts/extra_%dpx.png' % fontsize
38 try:
39 extraImage = Image.open(extraFilename)
40 extraImage = extraImage.convert('RGB');
42 except IOError:
43 print 'Missing extra symbol filename %s' % extraFilename
45 def getCharWidth(c):
46 if c in chars_extra:
47 if extraImage:
48 # Extra characters 16px
49 #if fontsize == 16:
50 if ord(c) <= 9:
51 return 13
52 else:
53 return 15
54 else:
55 return 0
56 elif c == " ":
57 return 4
58 else:
59 w, h = font.getsize(c)
60 return w + 1
62 def getFontWidth():
63 width = 0
64 for c in chars:
65 width += getCharWidth(c)
66 return width
68 width = getFontWidth()
69 image = Image.new('RGB', (width, fontsize + 4), background)
70 draw = ImageDraw.Draw(image)
72 width = 0
73 for c in chars:
74 coords.append(width)
76 if c in chars_extra:
77 if extraImage and c == chars_extra[0]:
78 image.paste(extraImage.copy(),(width,1))
79 elif c == " ":
80 pass
81 else:
82 w, h = font.getsize(c)
83 draw.text( (width + 1, fontoffset) , c, fill=foreground, font=font)
85 width += getCharWidth(c)
87 coords.append(width)
89 image.save(filename + ".png")
90 if coordsfile:
91 with open(filename + ".specs", "w") as f:
92 f.write(",".join(str(tmp) for tmp in coords))
95 # Main
96 if __name__ == "__main__":
97 createFontBitmap(sys.argv[4], sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), (0,0,0), (255,255,255))