PIL问题:加载任何字体库和使用unicode失败
我新安装了PIL。但我发现:
- 我无法使用加载任何字体库 "ImageFont.truetype("xxx.ttc", 50)" 等等。
- 当我将一些文本渲染为图像时, 并且文本是 unicode 包含 汉字我懂了 UnicodeEncodeError 类似:
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。谁能帮助我吗?提前致谢!
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, fill = "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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它在 Ubuntu10.10 和 python 2.6.6 上运行良好
也许尝试使用 tcc 字体的绝对路径?
这是完美运行的代码:
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: