PIL problems: failed in loading any font library and using unicode
I newly installed PIL. But I find:
- I can't load any font lib using "ImageFont.truetype("xxx.ttc", 50)" and the like.
- When I render some text to image, and the text is unicode containing Chinese characters, I get UnicodeEncodeError like:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u6211' in position 0: ordinal not in range(128)
The problem script is:
# -*- coding: utf-8 -*-
import sys
from PIL import Image
import ImageFont, ImageDraw
text = sys.argv[1]
if not isinstance(text, unicode):
text = text.decode('gbk')
filename = sys.argv[2]
image = Image.new("RGBA", (100, 100), (255,255,255))
usr_font = ImageFont.truetype("simsun.ttc", 50) #In fact, it can't load any font lib.
d_usr = ImageDraw.Draw(image)
d_usr = d_usr.text((10, 10), text, fil开发者_如何学JAVAl = "blue", font=usr_font) #error when text is Chinese
image.save(filename)
My OS is Windows7, with Python 2.5 installed. Can anyone help me? Thanks in advance!
It works fine on Ubuntu10.10 with python 2.6.6 Perhaps try using the absolute path to the tcc font?
This is the code that runs flawlessly:
#! /usr/bin/python
# -*- coding: utf-8 -*-
import Image
import ImageDraw
import ImageFont
ttfont = ImageFont.truetype ('/usr/share/fonts/truetype/wqy/wqy-microhei.ttc', 20)
text = u'我能有乾酪?'
image = Image.new ('RGB', (256, 128), 0xffffff);
ImageDraw.Draw (image).text ( (20, 20), text, font = ttfont, fill = (0, 0, 0) )
image.save ('chinese.jpg')
精彩评论