【问题标题】:How to load fonts from GCS如何从 GCS 加载字体
【发布时间】:2023-02-04 05:49:04
【问题描述】:

我想从 Google Storage 加载“字体”,我尝试了两种方法,但都不起作用。任何指针?感谢您提供的任何建议。

第一的:

我按照load_font_from_gcs(uri)在回答here中给出的说明进行操作,但我收到了一个NameError:未定义名称“load_font_from_gcs”信息。我安装了谷歌存储依赖并执行from google.cloud import storage

.

第二:

我尝试执行以下代码(参考 #1),并遇到 blob has no attribute open() 错误,与我在 here 得到的答案相同,但作为此 link 中的参考,它给出了肯定的答案。

参考#1

bucket = storage_client.bucket({bucket_name})
blob = bucket.get_blob({blob_name) 
with blob.open("r") as img:
  imgblob = Image.open(img)
  draw = ImageDraw.Draw(imgblob)

【问题讨论】:

  • 您是否尝试过不仅复制粘贴已接受的答案,而且首先了解它是如何工作的?
  • @Abraham Tugalov 更多解释,真的需要更积极和建设性的评论。谢谢你!

标签: python fonts path python-imaging-library gcs


【解决方案1】:

根据提供的链接,您的代码必须使用 BytesIO 才能使用从 GCS 加载的字体文件。
load_font_from_gcs 是一个自定义函数,由您引用的那个问题的作者编写。
它不在 google-cloud-storage 包中。

接下来,根据官方的谷歌云存储文档here
可以通过这种方式访问​​存储中的文件(此示例将字体文件加载到PIL.ImageFont.truetype):

# Import PIL
from PIL import Image, ImageFont, ImageDraw

# Import the Google Cloud client library
from google.cloud import storage

# Import BytesIO module
from io import BytesIO

# Instantiate a client
storage_client = storage.Client()

# The name of the bucket
bucket_name = "my-new-bucket"

# Required blob
blob_name = "somefont.otf"

# Creates the bucket & blob instance
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)

# Download the given blob
blob_content = blob.download_as_string()

# Make ImageFont out of it (or whatever you want)
font = ImageFont.truetype(BytesIO(font_file), 18)

因此,您的参考代码可以分别更改:

bucket = storage_client.bucket({bucket_name})
blob = bucket.get_blob({blob_name).download_as_string()
bytes = BytesIO(blob)
imgblob = Image.open(bytes)
draw = ImageDraw.Draw(imgblob)

您可以阅读更多关于 PIL here 的信息。
另外,不要忘记检查official Google Cloud Storage documentation
(有很多使用 Python 代码的示例。)

【讨论】:

  • 感谢您的详细解释和链接。它有助于。代码和查找相关官方文档
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 2011-02-13
  • 2012-11-21
  • 1970-01-01
  • 2022-12-15
相关资源
最近更新 更多