2013-03-31 25 views
2

我編寫了一個Python腳本,用於從字體中繪製字符,導出並將其發送到CGI界面進行顯示。但是,它不起作用。該代碼是如下:來自未由Python繪製的字體的圖像

#!/usr/bin/python 
# coding: UTF-8 
def getStringImage(text, font, size=40, color=[0,0,0]): 
    import Image, ImageDraw, ImageFont 
    img = Image.new("RGBA", (size, size), "white") 
    draw = ImageDraw.Draw(img) 
    draw.ink = color[0] + color[1]*256 + color[2]*256*256 
    font = ImageFont.truetype(font, size) 
    draw.text((0,0), text, font=font) 

    data = img.getdata() 
    newData = list() 
    for item in data: 
     if (item[0], item[1], item[2]) == (255, 255, 255): 
      newData.append((255, 255, 255, 0)) 
     else: 
      newData.append((item[0], item[1], item[2], 255)) 
    img.putdata(newData) 
    return img 

text = "" # U+E010 
font = "hzcdp01b.ttf" 
size = 100 
color = [0, 0, 0] 

img = getStringImage(text.decode('UTF-8'), font, size, color) 
print 'Content-Type: image/png' 
print 'Content-Disposition: inline; filename="image.png"' 
print 
import cStringIO 
f = cStringIO.StringIO() 
img.save(f, "png") 
f.seek(0) 
print f.read() 

上面使用的字體從該系統中提取:http://j.mp/14y6MAL,這裏是單個備份文件:http://j.mp/122PGLe

如果使用另一個字體(例如它工作正常「 mingliu.ttc「與char」人「)。

回答

0

確保要顯示的字符實際上映射到字形。當看着hzcdp01b.ttf,它似乎沒有字符映射表:

> fc-query hzcdp01b.ttf 
Pattern has 15 elts (size 16) 
    family: "hzcdp01b"(s) 
    slant: 0(i)(s) 
    weight: 80(i)(s) 
    width: 100(i)(s) 
    spacing: 100(i)(s) 
    foundry: "unknown"(s) 
    file: "hzcdp01b.ttf"(s) 
    index: 0(i)(s) 
    outline: FcTrue(s) 
    scalable: FcTrue(s) 
    charset: 
(s) 
    lang: (s) 
    fontversion: 69632(i)(s) 
    fontformat: "TrueType"(s) 
    decorative: FcFalse(s) 
+0

非常感謝您的答覆。看起來字形在文件中的某處,因爲這種字體[在安裝後可以在Windows上查看](http://ppt.cc/wQwg),並且可以用Visual Basic繪製。有沒有辦法將這些可用的字形映射到字體中?如何? –

+0

@DannyLin:你將不得不解析字體裏的'cmap'表。見例如[here](http://scripts.sil.org/cms/scripts/page.php?item_id=IWS-Chapter08)和[這裏](https://developer.apple.com/fonts/TTRefMan/RM06/Chap6的.html)。 –