如何在不指定绝对路径的情况下使用 PIL.ImageFont.truetype 加载字体文件? [英] How I can load a font file with PIL.ImageFont.truetype without specifying the absolute path?
问题描述
当我在Windows中编写代码时,这段代码可以很好地加载字体文件:
ImageFont.truetype(filename='msyhbd.ttf', size=30);
我猜字体位置是在 Windows 注册表中注册的.但是当我将代码移到 Ubuntu,并将字体文件复制到/usr/share/fonts/时,代码找不到字体:
self.font = core.getfont(字体、大小、索引、编码)IOError: 无法打开资源
如何让PIL在不指定绝对路径的情况下找到ttf文件?
根据PIL文档,只搜索Windows字体目录:
<块引用>在 Windows 上,如果给定的文件名不存在,加载器也会在 Windows 字体目录中查找.
http://effbot.org/imagingbook/imagefont.htm
所以你需要自己编写代码来搜索Linux上的完整路径.
但是,PIL 分支,Pillow 目前有一个 PR 来搜索 Linux 目录.目前尚不清楚要搜索所有 Linux 变体的目录,但您可以在此处查看代码,并可能对 PR 有所贡献:
https://github.com/python-pillow/Pillow/pull/682>
When I write the code in Windows, this code can load the font file just fine:
ImageFont.truetype(filename='msyhbd.ttf', size=30);
I guess the font location is registered in Windows registry. But when I move the code to Ubuntu, and copy the font file over to /usr/share/fonts/, the code cannot locate the font:
self.font = core.getfont(font, size, index, encoding)
IOError: cannot open resource
How can I get PIL to find the ttf file without specifying the absolute path?
According to the PIL documentation, only Windows font directory is searched:
On Windows, if the given file name does not exist, the loader also looks in Windows fonts directory.
http://effbot.org/imagingbook/imagefont.htm
So you need to write your own code to search for the full path on Linux.
However, Pillow, the PIL fork, currently has a PR to search a Linux directory. It's not exactly clear yet which directories to search for all Linux variants, but you can see the code here and perhaps contribute to the PR:
https://github.com/python-pillow/Pillow/pull/682
这篇关于如何在不指定绝对路径的情况下使用 PIL.ImageFont.truetype 加载字体文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!