首页 > 解决方案 > 将字体从 URL 加载到 Pillow

问题描述

有没有办法直接从 url 加载带有 Pillow 库的字体,最好是加载到 Google Colab 中?我尝试了类似的东西

from PIL import Image, ImageDraw, ImageFont ImageFont.truetype("https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true", 15)

然而我得到一个错误OSError: cannot open resource。我也尝试过使用谷歌字体,但无济于事。 在此处输入图像描述

标签: pythonpython-3.xpython-imaging-librarygoogle-colaboratory

解决方案


您可以
(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

推荐阅读