5

I'm writing a script that takes my grades from my school grade website and draws the grades onto an image and saves it as my background and I'm trying to change the font when i draw the text onto the image but I'm getting an error

Here is the code I'm trying:

font = ImageFont.load('C:\WINDOWS\Fonts\CALIBRI.TTF')
img = Image.open('bg.bmp')
draw = ImageDraw.Draw(img)

now = datetime.datetime.now()


draw.text((625, 425),'                      CURRENT GRADES' )
draw.text((625, 475), 'Period 1: Geography -----------------------------{0}'.format(a),("blue"),(font))
draw.text((625, 525), 'Period 2: Francais-------------------------------{0}'.format(b),("red"),(font))
draw.text((625, 575), 'Period 3: Science--------------------------------{0}'.format(c),("orange"),(font))
draw.text((625, 625), 'Period 4: P.E------------------------------------{0}'.format(d),("blue"),(font))
draw.text((625, 675), 'Period 5: Algebra 9------------------------------{0}'.format(e),("red"),(font))
draw.text((625, 725), 'Period 6: LA-------------------------------------{0}'.format(f),("orange"),(font))
draw.text((625, 775), 'Last Updated: {0}'.format(now))

img.save('mod_bg.bmp')

but when i do this i get this error message:

Traceback (most recent call last):
  File "C:\Python27\Project.py", line 45, in <module>
     font = ImageFont.load('C:\WINDOWS\Fonts\CALIBRI.TTF')
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 193, in load
    f._load_pilfont(filename)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 91, in _load_pilfont
    raise IOError("cannot find glyph data file")
IOError: cannot find glyph data file

can anyone tell me why this isn't working and what i should do instead

4

2 回答 2

9

和函数应该load()load_path()用于位图字体文件。由于您正在尝试加载TrueType字体 (.ttf),因此您应该使用该truetype()函数。

from PIL import ImageFont
font = ImageFont.truetype(r'C:\WINDOWS\Fonts\CALIBRI.TTF')

自您发布问题以来,PIL / Pillow 库可能已经更改,因此我建议您查阅您正在使用的库的相应文档。

旁注 - 在字符串文字(尤其是 Windows 文件路径)中使用反斜杠时要小心。反斜杠是转义字符。例如,'\n'是单个换行符,而不是两个字符。您应该使用另一个反斜杠 ( 'C:\\WINDOWS\\Fonts\\CALIBRI.TTF') 转义每个反斜杠,或者使用“原始”字符串文字来防止反斜杠被解释 ( r'C:\WINDOWS\Fonts\CALIBRI.TTF')。

当有疑问时,print()它就出来了。

于 2017-12-27T20:24:07.067 回答
1

我遇到了这个错误,我相信这是因为你安装的 PIL 是在没有 libfreetype 的情况下编译的。为此,您必须安装 freetype2 然后编译 PIL。看

Python:未安装 _imagingft C 模块

或者,您可以尝试 Pillow,它是 PIL 库的更新分支

https://pypi.python.org/pypi/Pillow/2.0.0

于 2013-05-10T02:53:58.567 回答