Version 3, last updated by guitch at February 10, 2010 15:20 UTC

Images de polices d'écriture avec python

On peut facilement afficher (et sauvegarder) des images de fontes avec PIL (Python Image Library). L'exemple suivant parcourt le dossier font_dir et génère des images JPEG des lettres de l'alphabet (majuscules et minuscules) et de chiffres de 0 à 9 pour chaque police, dans image_dir.

#!/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 tff 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")