将字体从URL加载到枕头 记忆速度

问题描述

有没有一种方法可以直接从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字体,但无济于事。

enter image description here

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...