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.

7 comments:

  1. Your post saved my day!

    谢谢

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

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

    ReplyDelete
  4. Thanks! Very useful.

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

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

    ReplyDelete
  7. Thanks a lot for your snippet ! Fantastic for french!

    ReplyDelete