python - 将字体从 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)
解决方案
您可以
(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
推荐阅读
- arrays - 如何使用powershell将对象添加到json文件中的空白数组
- php - CakePHP 3.10 -> 4.x 升级 - Rector 无法启动
- javascript - 将变量从组件实时传递到索引reactJS
- python-3.x - 允许直接访问 Document AI 的本地文件
- javascript - 使用 React 通过多个按钮减少代码冗余
- lda - LDA Gibbs 对方程推导的抽样混淆
- java - 我如何格式化用逗号分隔的字符串
- angular - 为在开放层中为 angular 8 创建的图像添加边框
- knex.js - 使用值列表过滤多对多关系
- r - 如何使用 R 中的现有数据更新整个表?