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.


Régis said...

Your post saved my day!


Anonymous said...

Mine too! My umlaut-problem is now fixed. thnx

Paolo said...

Very very useful code snippet!!
You solved my problem too (with italian accents ;-)
Thank you!

Anonymous said...

Thanks! Very useful.

Trent McCoy said...

Still useful at 2011, I needed it for spanish accents :-P
Thank you!

Endless Nameless said...

Wow, this is amazing. Worked like a charm for Portuguese too.

Anonymous said...

Thanks a lot for your snippet ! Fantastic for french!