PIL问题:加载任何字体库和使用unicode失败

发布于 2024-11-06 14:22:21 字数 846 浏览 0 评论 0原文

我新安装了PIL。但我发现:

  1. 我无法使用加载任何字体库 "ImageFont.truetype("xxx.ttc", 50)" 等等。
  2. 当我将一些文本渲染为图像时, 并且文本是 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:

  1. I can't load any font lib using
    "ImageFont.truetype("xxx.ttc", 50)"
    and the like.
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倚栏听风 2024-11-13 14:22:21

它在 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')

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文