访问Colab中提取的zip文件

时间:2020-11-07 16:57:56

标签: python python-requests python-imaging-library zipfile colab

这里有一些案例研究。我正在尝试使用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)

但是如何从本地内存中读取文件?

完整图片,便于查看: enter image description here

1 个答案:

答案 0 :(得分:1)

您只需将文件名提供给ImageFont.truetype(),因此请更改此行:

font = ImageFont.truetype(open("Roboto-BlackItalic.ttf"), 72)

font = ImageFont.truetype("Roboto-BlackItalic.ttf", 72)