python - 将文本绘制到图像时出现字体错误

标签 python fonts python-imaging-library

我正在编写一个脚本,从我的学校成绩网站获取我的成绩并将成绩绘制到图像上并将其保存为我的背景,当我将文本绘制到图像上时我试图更改字体但是我出现错误

这是我正在尝试的代码:

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

但是当我这样做时,我收到了这个错误信息:

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

谁能告诉我为什么这不起作用以及我应该怎么做

最佳答案

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() 出来。

关于python - 将文本绘制到图像时出现字体错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409484/

相关文章:

python - 在 Windows 中限制 python 脚本 RAM 使用

python - Slack API 服务的测试 token 是否用完?

python - 将 PIL 图像转换为张量时,为什么像素会发生变化?

python - 无法通过 pip 安装 Pillow

python - 比较两个类列表对象的内容的最佳方法是什么?

python - 更改散点图标记粗细

html - CSS 字体无法在设备上正确显示

python - 如何仅更改图例字体而不影响 matplotlib 中的其他参数?

html - 如何使字体 FuturaPtBooks 在 html 中可用

python - PIL : draw transparent text on top of an image