You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Google Cloud Storage加载字体?两种尝试均失败求指导

从Google Cloud Storage加载字体的问题解决方法

问题1:load_font_from_gcs未定义错误

  • 这个函数不是Google Cloud Storage SDK的内置函数,是Stack Overflow回答里用户自定义的方法,需要自己实现。示例实现如下:
from google.cloud import storage
from PIL import ImageFont

def load_font_from_gcs(uri):
    # 解析GCS URI(格式示例:gs://bucket_name/font_file.ttf)
    bucket_name = uri.split('/')[2]
    font_path = '/'.join(uri.split('/')[3:])
    
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(font_path)
    
    # 下载字体到内存并加载
    font_bytes = blob.download_as_bytes()
    font = ImageFont.truetype(font_bytes, size=24)  # size按需调整
    return font
  • 使用时直接调用该自定义函数,传入正确的GCS URI即可。

问题2:blob has no attribute open()错误

  • 核心解决思路:
    1. 升级SDK版本:blob.open()是较新版本的google-cloud-storage才支持的方法,先执行升级命令:
      pip install --upgrade google-cloud-storage
      
    2. 修正文件打开模式:字体是二进制文件,必须用"rb"模式打开,同时调整加载逻辑,修正后的代码示例:
      from google.cloud import storage
      from PIL import Image, ImageDraw, ImageFont
      
      storage_client = storage.Client()
      bucket = storage_client.bucket("你的Bucket名称")
      blob = bucket.get_blob("字体文件路径,如fonts/xxx.ttf")
      
      with blob.open("rb") as font_file:
          font = ImageFont.truetype(font_file, size=24)
          # 示例绘图逻辑
          img = Image.new("RGB", (500, 200), "white")
          draw = ImageDraw.Draw(img)
          draw.text((50, 50), "测试文本", font=font, fill="black")
          img.save("output.png")
      
  • 若不想升级SDK,可改用download_as_bytes()替代open():
    font_bytes = blob.download_as_bytes()
    font = ImageFont.truetype(font_bytes, size=24)
    

内容的提问来源于stack exchange,提问作者april

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:55:43