2011-05-11 75 views
0

我新安装了PIL。但我发现:PIL问题:加载任何字体库和使用unicode失败

  1. 我无法加载任何字体的lib使用 “ImageFont.truetype(” xxx.ttc “50)” 等。
  2. 当我呈现一些文本图像, 和文本是包含 中国字符的Unicode,我得到 UnicodeEncodeError像:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u6211' in position 0: ordinal not in range(128)

问题脚本是:

# -*- 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, fill = "blue", font=usr_font) #error when text is Chinese 
image.save(filename) 

我OS是Windows7,安装了Python 2.5。谁能帮我?提前致谢!

回答

0

它在Ubuntu10.10上使用python 2.6.6很好 也许尝试使用tcc字体的绝对路径?

这是一个运行完美的代码:

#! /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') 
+0

非常感谢您!我发现了两个错误:1)我使用的字体在我的计算机上不存在,或者名称没有正确的路径。 2)当由汉字组成的Unicode字符串被渲染为图像时,需要中文字体!否则PIL抱怨UnicodeEncodeError,这可能会误导恕我直言。 – Robert 2011-05-12 07:12:37