comparison transformations/ttf2jpg.py @ 6:424b5b0d9fcb

Image generation from fonts added
author guitch
date Tue, 26 Jan 2010 17:09:16 -0500
parents
children 6d432a5010a2
comparison
equal deleted inserted replaced
5:8d1c37190122 6:424b5b0d9fcb
1 #!/usr/bin/python
2 # -*- coding: iso-8859-1 -*-
3 # ttf2jpg.py converts font files to jpg images
4 # download fonts from http://www.dafont.com
5
6 ##################
7 # import libraries
8 ##################
9
10 import sys, os, fnmatch
11 import Image
12 import ImageFont, ImageDraw
13
14 ###########
15 # variables
16 ###########
17 # don't forget the "/" at the end of directories
18
19 font_dir = "/usr/share/fonts/truetype/ttf-liberation/"
20 image_dir = "./images/"
21 pattern = "*.ttf"
22
23 ###########
24 # functions
25 ###########
26
27 # save a picture of "text" with font "font_file"
28 def write_image(text, font_file):
29 # print "Writing \"" + text + "\" with " + font_file + "..."
30 sys.stdout.write(".")
31 sys.stdout.flush()
32
33 # create a 32x32 white picture, and a drawing space
34 image = Image.new("L", (32, 32), "White")
35 draw = ImageDraw.Draw(image)
36
37 # load the font with the right size
38 font = ImageFont.truetype(font_dir + font_file, 28)
39 w,h = draw.textsize(text, font=font)
40
41 # write text and aligns it
42 draw.text(((32 - w) / 2, ((32 - h) / 2)), text, font=font)
43
44 # show image, xv must be installed
45 #image.show()
46
47 # save the picture
48 image.save(image_dir + text + "-" + font_file + ".jpg")
49
50 # write all the letters and numbers into pictures
51 def process_font(font_file):
52 for i in range(0, 26):
53 write_image(chr(ord('a') + i), font_file)
54 for i in range(0, 26):
55 write_image(chr(ord('A') + i), font_file)
56 for i in range(0, 10):
57 write_image(chr(ord('0') + i), font_file)
58
59 ######
60 # main
61 ######
62
63 # look for ttf files
64 files = os.listdir(font_dir)
65 font_files = fnmatch.filter(files, pattern)
66
67 # create "image_dir" if it doesn't exist
68 if not os.path.isdir(image_dir):
69 os.mkdir(image_dir)
70
71 sys.stdout.write( str(len(font_files)) + " fonts found, generating jpg images in folder " + image_dir )
72 sys.stdout.flush()
73
74 # main loop
75 for font_file in font_files:
76 process_font(font_file)
77
78 sys.stdout.write("\nall done!\n")