问题描述
有没有一种方法可以直接从url(最好是Google Colab)加载带有Pillow库的字体?我尝试过类似
from PIL import Image,ImageDraw,ImageFont
ImageFont.truetype("https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true",15)
但是我收到了 OSError:无法打开资源的错误。我也尝试过Google字体,但无济于事。
解决方法
您可以
(1)使用urllib.request.urlopen()
通过HTTP GET请求获取字体。
(2)使用@functools.lrucache或@memoization.cache记住结果,这样就不会在每次运行函数和
时都提取字体
(3)使用io.BytesIO
from PIL import ImageFont
import urllib.request
import functools
import io
@functools.lru_cache
def get_font_from_url(font_url):
return urllib.request.urlopen(font_url).read()
def webfont(font_url):
return io.BytesIO(get_font_from_url(font_url))
if __name__ == "__main__":
font_url = "https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true"
with webfont(font_url) as f:
imgfnt = ImageFont.truetype(f,15)
还有python-memoization(pip install memoization
)用于替代记忆方式。用法是
from memoization import cache
@cache
def get_font_from_url(font_url):
return urllib.request.urlopen(font_url).read()
记忆速度
没有备注:
In [1]: timeit get_font_from_url(font_url)
The slowest run took 4.95 times longer than the fastest. This could mean that an intermediate result is being cached.
1.32 s ± 1.11 s per loop (mean ± std. dev. of 7 runs,1 loop each)
带有备注:
In [1]: timeit get_font_from_url(font_url)
The slowest run took 11.00 times longer than the fastest. This could mean that an intermediate result is being cached.
271 ns ± 341 ns per loop (mean ± std. dev. of 7 runs,1 loop each)
```t
,
尝试这样:
import requests
from io import BytesIO
req = requests.get("https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true")
font = ImageFont.truetype(BytesIO(req.content),72)