【发布时间】:2020-11-07 16:57:56
【问题描述】:
这里有一些案例研究。我正在尝试在 Google Colab 中使用 PIL 库,但无法让 ImageFont 读取我最初的压缩文件。代码:
import requests, zipfile, io
r3 = requests.get('https://sources.archlinux.org/other/community/ttf-roboto/ttf-roboto-hinted-2.138.zip')
z3 = zipfile.ZipFile(io.BytesIO(r3.content))
z3.extractall()
到目前为止一切顺利,如果我用 ls 浏览我的目录,它会向我显示元素:
ls
演出:
LICENSE RobotoCondensed-Regular.ttf
__MACOSX/ Roboto-Italic.ttf
Roboto-BlackItalic.ttf Roboto-LightItalic.ttf
Roboto-Black.ttf Roboto-Light.ttf
Roboto-BoldItalic.ttf Roboto-MediumItalic.ttf
Roboto-Bold.ttf Roboto-Medium.ttf
RobotoCondensed-BoldItalic.ttf Roboto-Regular.ttf
RobotoCondensed-Bold.ttf Roboto-ThinItalic.ttf
RobotoCondensed-Italic.ttf Roboto-Thin.ttf
RobotoCondensed-LightItalic.ttf sample_data/
RobotoCondensed-Light.ttf
现在让我们导入 ImageFont
from PIL import ImageFont
如何读取文件?如果我试试这个:
# how do I make it work if I read it from the extracted files?
font = ImageFont.truetype(open("Roboto-BlackItalic.ttf"), 72)
失败并出现错误:
'utf-8' 编解码器无法解码位置 7 中的字节 0x80:无效的起始字节
我知道我可以将直接链接传递给请求,它会起作用:
# it works if we pass a direct link to requests like this:
req = requests.get("https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true")
font = ImageFont.truetype(io.BytesIO(req.content), 72)
但是如何从本地内存中读取文件呢?
【问题讨论】:
标签: python python-requests python-imaging-library zipfile google-colaboratory