Skip to main content
 首页 » 编程设计

Python 图像库,ImageFont IOError

2025年05月04日11TianFang

我的 python-FotoBox-Script 在我的 Ubuntu labtop 上工作得很好,但是在运行 Raspbian 的 Raspberry-Pi 上脚本有以下问题:

pi@raspberrypi:~/Desktop/FotoBox $ python PythonCollage_31.py 
    Traceback (most recent call last): 
      File "PythonCollage_31.py", line 49, in <module> 
        font = ImageFont.truetype("/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf", 80, 0, 'unic') 
      File "/usr/lib/python2.7/dist-packages/PIL/ImageFont.py", line 240, in truetype 
        return FreeTypeFont(font, size, index, encoding) 
      File "/usr/lib/python2.7/dist-packages/PIL/ImageFont.py", line 137, in __init__ 
        self.font = core.getfont(font, size, index, encoding) 
    IOError: unknown file format 

我还尝试使用另一行代码创建字体对象:

font = ImageFont.truetype("/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf", 80) 

但结果相同。

当然,带有该字体的文件存在!

pi@raspberrypi:~/Desktop/FotoBox $ ls -l /usr/share/fonts/truetype/msttcorefonts/ 
insgesamt 4 
-rw-r--r-- 1 root root 128 Jun 17 22:04 Comic_Sans_MS.ttf 

请您参考如下方法:

ImageFont.truetype 的正确语法是这样的:

ImageFont.truetype(file, size, encoding=value) 

因此,如果您将 encoding= 添加到第四个参数的开头,使用 ""而不是 '',并删除第三个参数,则应该如下所示:

ImageFont.truetype("/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf", 80, 
encoding="unic") 

这对我有用。