遇到这个问题,在网上找了一天也没找到准确的解决方法,通过大量测试,发现了关键点,所以记录下来,让后面遇到相同问题的人一些思路,避免进坑。
在图上绘上字符,可以使用如下的方法,但是需要特点的字体时,需要在网上的字体网站下载相关的字体,一般都是ttf格式,然后把它复制到c:/windows/fonts里面,会自动完成安装。但是安装后,选择文件,右键属性看他的地址。
from PIL import ImageFont, Image, ImageDraw
fontpath="C:\\Users\\Administrator\\AppData\\Local\\Microsoft\\Windows\\Fonts\\Creepster.ttf"
font = ImageFont.truetype(fontpath, size=600, index=0)
img_pil = Image.fromarray(img_temp)
draw = ImageDraw.Draw(img_pil)
draw.text((50, -50), str, font=font, fill=(255, 255, 255))
运行上面的代码,字体已经修改为自己下载的字体(在此觅知网站可下载,需要收费),就会出现下面的错误,使用默认的字体路径,不会出现,比如:fontpath="C:\\Windows\\Fonts\\simsun.ttc"
提示的错误如下:
font = ImageFont.truetype(fontpath, size=300, index=0)
File "C:\Users\Administrator\anaconda3\envs\env_m\lib\site-packages\PIL\ImageFont.py", line 878, in truetype
return freetype(font)
File "C:\Users\Administrator\anaconda3\envs\env_x\lib\site-packages\PIL\ImageFont.py", line 875, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\Administrator\anaconda3\envs\env_x\lib\site-packages\PIL\ImageFont.py", line 227, in __init__
font, size, index, encoding, layout_engine=layout_engine
OSError: cannot open resource
解决方法,其实很简单:
只要Creepster.ttf" 修改为 creepster.ttf , 首字母要小写。