# HG changeset patch # User guitch # Date 1264543756 18000 # Node ID 424b5b0d9fcb08f772567eed6dfb2d450e8a8e3b # Parent 8d1c3719012254e9e5c9ac303474c7fae9da3201 Image generation from fonts added diff -r 8d1c37190122 -r 424b5b0d9fcb transformations/ttf2jpg.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/transformations/ttf2jpg.py Tue Jan 26 17:09:16 2010 -0500 @@ -0,0 +1,78 @@ +#!/usr/bin/python +# -*- coding: iso-8859-1 -*- +# ttf2jpg.py converts font files to jpg images +# download fonts from http://www.dafont.com + +################## +# import libraries +################## + +import sys, os, fnmatch +import Image +import ImageFont, ImageDraw + +########### +# variables +########### +# don't forget the "/" at the end of directories + +font_dir = "/usr/share/fonts/truetype/ttf-liberation/" +image_dir = "./images/" +pattern = "*.ttf" + +########### +# functions +########### + +# save a picture of "text" with font "font_file" +def write_image(text, font_file): +# print "Writing \"" + text + "\" with " + font_file + "..." + sys.stdout.write(".") + sys.stdout.flush() + + # create a 32x32 white picture, and a drawing space + image = Image.new("L", (32, 32), "White") + draw = ImageDraw.Draw(image) + + # load the font with the right size + font = ImageFont.truetype(font_dir + font_file, 28) + w,h = draw.textsize(text, font=font) + + # write text and aligns it + draw.text(((32 - w) / 2, ((32 - h) / 2)), text, font=font) + + # show image, xv must be installed + #image.show() + + # save the picture + image.save(image_dir + text + "-" + font_file + ".jpg") + +# write all the letters and numbers into pictures +def process_font(font_file): + for i in range(0, 26): + write_image(chr(ord('a') + i), font_file) + for i in range(0, 26): + write_image(chr(ord('A') + i), font_file) + for i in range(0, 10): + write_image(chr(ord('0') + i), font_file) + +###### +# main +###### + +# look for ttf files +files = os.listdir(font_dir) +font_files = fnmatch.filter(files, pattern) + +# create "image_dir" if it doesn't exist +if not os.path.isdir(image_dir): + os.mkdir(image_dir) + +sys.stdout.write( str(len(font_files)) + " fonts found, generating jpg images in folder " + image_dir ) +sys.stdout.flush() + +# main loop +for font_file in font_files: + process_font(font_file) + +sys.stdout.write("\nall done!\n") \ No newline at end of file