3/3/06

How to create images from Chinese text using PIL

Here's how to create images from Chinese text using PIL (python image library).

We need Chinese fonts. The fonts in Linux doesn't work. For example, pilfont.py can't convert the font file 'fangsongti24.pcf' located in my '/usr/share/fonts/bitmap-fonts/' directory. Fortunately we can use truetype fonts in Windows. Get a chinese font (I chose simsun.ttc) from Windows's 'windows/fonts' directory, and copy it to linux.
To draw Chinese text correctly into image file, use unicode. The following is an example:
#-*- coding:utf8 -*-
import sys
import Image
import ImageDraw
import ImageFont

txt = '你好,世界!'

font = ImageFont.truetype('simsun.ttc',24)

im = Image.new("RGBA",(300,200),(0,0,0))

draw = ImageDraw.Draw(im)

#draw.text( (0,50), u'你好,世界!', font=font)
draw.text( (0,50), unicode(txt,'UTF-8'), font=font)

del draw

im.save(sys.stdout, "PNG")

That's it.