我新安装了PIL。但我发现:
UnicodeEncodeError:'ascii'编解码器 无法对字符u'\ u6211'进行编码 位置0:序数不在范围内(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)
我的操作系统是Windows7,安装了Python 2.5。谁能帮我?提前谢谢!
答案 0 :(得分:0)
在使用python 2.6.6的Ubuntu10.10上运行正常 也许尝试使用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')