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

GCP Gemini API本地图片多模态请求:替代Part.from_uri的方法

加载本地图片到Vertex AI多模态模型的解决方案

问题描述

使用Google Vertex AI的Gemini生成式模型时,官方示例通过Part.from_uri加载云存储图片可正常运行,但尝试加载本地图片时,按文档编写的代码抛出异常:

from PIL import Image

image_part = Part.from_image(Image.load_from_file("image.jpg"))
response = model.generate_content([image_part,"what is this image?"])

异常信息:

module 'PIL.Image' has no attribute 'load_from_file'

可行的本地图片加载方法

方法1:直接使用Part.from_file(推荐)

Part类提供了直接加载本地文件的方法,无需额外依赖PIL,代码更简洁:

from vertexai.generative_models import GenerativeModel, Part

# 初始化模型(省略项目ID、区域等初始化代码)
model = GenerativeModel(model_name="gemini-1.5-flash-001")

# 加载本地图片
image_part = Part.from_file("image.jpg")

# 发送多模态请求
response = model.generate_content([image_part, "这张图片是什么?"])
print(response.text)

方法2:配合PIL正确加载图片

如果需要对图片做预处理(如裁剪、缩放),可先用PIL打开图片,再传入Part.from_image:

from PIL import Image
from vertexai.generative_models import GenerativeModel, Part

model = GenerativeModel(model_name="gemini-1.5-flash-001")

# 用PIL正确打开本地图片
img = Image.open("image.jpg")
# 可选:添加图片预处理逻辑,例如 img = img.resize((512, 512))

image_part = Part.from_image(img)
response = model.generate_content([image_part, "这张图片是什么?"])
print(response.text)

方法3:读取文件字节流

如果需要从内存中处理图片(如网络下载的字节数据),可读取文件字节后创建Part:

from vertexai.generative_models import GenerativeModel, Part

model = GenerativeModel(model_name="gemini-1.5-flash-001")

# 读取本地图片字节
with open("image.jpg", "rb") as f:
    image_bytes = f.read()

image_part = Part.from_data(data=image_bytes, mime_type="image/jpeg")
response = model.generate_content([image_part, "这张图片是什么?"])
print(response.text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:33:19