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

如何在Python中将Google Storage的JPG读取为路径或文件类型?

解决方案:Google Cloud Function中读取GCS JPG用于文本检测

先解决download_as_bytes()报错的核心问题

你大概率是两个原因导致报错:要么没正确获取Blob对象(比如误把Bucket实例当成了Blob),要么google-cloud-storage库版本太旧(旧版本方法名为download_as_string(),新版本才是download_as_bytes())。


方法1:读取为字节流(推荐,无需临时文件)

适合大部分文本检测库(比如Tesseract、Google Vision API),直接把字节流转成图像对象即可,不需要生成物理文件路径。

完整代码示例

import os
import io
from google.cloud import storage
from PIL import Image
import pytesseract  # 示例用的文本检测库,根据你的需求替换

def process_gcs_image(event, context):
    # 从Cloud Function触发事件中获取GCS路径(手动调用可直接指定gs路径)
    gs_path = f"gs://{event['bucket']}/{event['name']}"
    
    # 解析GS路径,拆分bucket和blob名称
    bucket_name = gs_path.split("/")[2]
    blob_name = "/".join(gs_path.split("/")[3:])
    
    # 初始化GCS客户端(Cloud Function中无需手动传密钥,默认用服务账号权限)
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)  # 这里才是正确的Blob对象
    
    # 下载为字节流
    image_bytes = blob.download_as_bytes()
    
    # 转成PIL图像对象,用于文本检测
    image = Image.open(io.BytesIO(image_bytes))
    text = pytesseract.image_to_string(image)
    
    # 后续处理文本结果...
    print(f"检测到文本:{text}")

方法2:读取为临时文件路径(适合要求输入文件路径的检测库)

如果你的文本检测工具必须要物理文件路径,可利用Cloud Function的/tmp临时目录(唯一可写目录)生成临时文件:

import tempfile
import os
from google.cloud import storage

def process_gcs_image(event, context):
    gs_path = f"gs://{event['bucket']}/{event['name']}"
    bucket_name = gs_path.split("/")[2]
    blob_name = "/".join(gs_path.split("/")[3:])
    
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    
    # 创建临时JPG文件
    with tempfile.NamedTemporaryFile(mode='wb', suffix='.jpg', delete=False, dir='/tmp') as temp_file:
        blob.download_to_file(temp_file)
        temp_file_path = temp_file.name
    
    # 用临时文件路径调用文本检测
    # 示例:text_detection_tool(temp_file_path)
    
    # 用完后可手动删除临时文件(可选,Cloud Function结束后会自动清理/tmp)
    os.unlink(temp_file_path)

关键配置说明

  1. 依赖包配置:在Cloud Function的requirements.txt中添加必要依赖:
google-cloud-storage>=2.15.0
Pillow>=10.0.0
pytesseract>=0.3.10

(如果用Google Vision API,替换成google-cloud-vision>=3.0.0)

  1. 权限配置:确保Cloud Function的默认服务账号拥有GCS存储桶的storage.objects.get权限(可在GCS存储桶的IAM设置中添加)。

  2. 版本兼容:如果还是报download_as_bytes不存在,要么把google-cloud-storage版本指定为2.x以上,要么改用旧版本方法blob.download_as_string()(推荐升级版本)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:55:14