来自不是由Python绘制的字体的图像

时间:2013-03-31 16:48:16

标签: python true-type-fonts

我编写了一个Python脚本,用于从字体中绘制字符,导出并将其发送到CGI界面进行显示。但是,它不起作用。代码如下:

#!/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“人”),它可以正常工作。

1 个答案:

答案 0 :(得分: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)