+
95
-

回答

api接口的话可以传入图片的url地址,我们以php为例

<?php

$openaiApiKey = "YOUR_OPENAI_API_KEY"; // 替换为您的 OpenAI API 密钥

$url = "https://api.openai.com/v1/chat/completions";

$data = array(
    "model" => "gpt-4-vision-preview",
    "messages" => array(
        array(
            "role" => "user",
            "content" => array(
                array(
                    "type" => "text",
                    "text" => "What’s in this image?"
                ),
                array(
                    "type" => "image_url",
                    "image_url" => array(
                        "url" => "https://repo.bfw.wiki/bfwrepo/image/61e27364c2151.png?x-oss-process=image/auto-orient,1/resize,m_fill,w_100,h_100,/quality,q_90"
                    )
                )
            )
        )
    ),
    "max_tokens" => 300
);

$data_string = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $openaiApiKey
));

$result = curl_exec($ch);

curl_close($ch);

// 处理结果
echo $result;

?>

还支持base64及python

import base64
import requests

# OpenAI API Key
api_key = "YOUR_OPENAI_API_KEY"

# Function to encode the image
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

# Path to your image
image_path = "path_to_your_image.jpg"

# Getting the base64 string
base64_image = encode_image(image_path)

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

payload = {
    "model": "gpt-4-vision-preview",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "What’s in this image?"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": f"data:image/jpeg;base64,{base64_image}"
            }
          }
        ]
      }
    ],
    "max_tokens": 300
}

response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)

print(response.json())

网友回复

我知道答案,我要回答