2011-05-11 34 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