PHP 8.3 无法直接上传图片调用 Gemini API,因 Gemini 不支持 multipart/form-data 文件上传;需将图片 base64 编码或上传至 GCS 后通过 URI 引用,再以 JSON payload 发送至 Gemini 模型接口。

PHP 8.3 本身不能直接调用 Gemini API 上传图片识别内容,因为 Gemini API(由 Google 提供)目前不支持图片上传和多模态识别功能 —— 截至 2024 年底,Gemini 的官方 REST API(如 v1beta/models/gemini-pro-vision)已下线,gemini-1.5-pro 等模型虽支持图像输入,但仅限于通过 Google AI Studio 或 Vertex AI SDK,且要求图像以 base64 编码字符串或 Google Cloud Storage (GCS) URI 形式传入,不接受 multipart/form-data 文件上传。
确认你用的是 Gemini 的哪个接口
Google 目前提供两类主要接入方式,适用场景不同:
- Google AI Studio(免费、简单):适合测试和轻量调用,支持 base64 图片,但有配额限制(每日约 60 次图像请求),不支持服务端长期部署;
- Vertex AI(生产级、需 GCP 项目):需启用 Vertex AI API、授权服务账号、配置 IAM,支持 base64 和 GCS URI,可集成到 PHP 后端,但流程较重。
⚠️ 注意:没有 /upload 或 /vision 等独立上传接口,图片必须作为请求 payload 的一部分(base64)或引用(GCS),不是传统“文件上传”。
PHP 8.3 调用 Gemini(以 gemini-1.5-flash 为例)—— base64 方式
适用于小图(≤ 20MB,推荐 ≤ 4MB),需先将图片读取并编码:
立即学习“PHP免费学习笔记(深入)”;
- 用
file_get_contents()读取本地图片(确保 PHP 有读取权限); - 用
base64_encode()编码为字符串; - 构造 JSON payload,按 Gemini 要求格式组织
contents数组,含parts(文本 + 图像 data); - 使用
cURL或file_get_contents()with stream context 发送 POST 请求,Header 必须含Content-Type: application/json和有效的Authorization: Bearer YOUR_API_KEY。
示例关键代码片段:
$imagePath = '/path/to/photo.jpg';
$imageData = file_get_contents($imagePath);
$base64Image = base64_encode($imageData);
$payload = [
'contents' => [[
'parts' => [
['text' => '请描述这张图片的内容,用中文回答。'],
['inline_data' => [
'mime_type' => 'image/jpeg',
'data' => $base64Image
]]
]
]],
];
$jsonPayload = json_encode($payload);
$apiKey = 'your_api_key_here'; // 来自 Google AI Studio 或 Vertex AI
$ch = curl_init('https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' . $apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if (isset($result['candidates'][0]['content']['parts'][0]['text'])) {
echo $result['candidates'][0]['content']['parts'][0]['text'];
}
替代方案:用 GCS + Vertex AI(适合生产环境)
若图片较大或需高并发,推荐上传到 Google Cloud Storage,再把 gs://bucket-name/object.jpg URI 传给 Gemini:
- 安装
google/cloud-storageComposer 包; - 用服务账号密钥初始化 StorageClient;
- 上传图片到 GCS(设置公开读或让 Vertex AI 有访问权限);
- 在 Gemini 请求中改用
file_data字段,指定file_uri和mime_type; - 注意:GCS bucket 需与 Vertex AI 所在区域兼容,且服务账号需有
roles/storage.objectViewer权限。
常见问题提醒
-
API Key 安全:切勿硬编码或暴露在前端,应存于环境变量(
$_ENV['GEMINI_API_KEY'])或配置中心; -
MIME 类型必须准确:JPEG 用
image/jpeg,PNG 用image/png,错误会导致 400; -
响应结构嵌套深:结果在
$result['candidates'][0]['content']['parts'][0]['text'],需逐层判断是否存在; -
错误处理不可少:检查 HTTP 状态码、
error字段(如429配额超限、400格式错误); - PHP 8.3 兼容性无问题:cURL、JSON、base64 等均为内置扩展,无需额外适配。



















