MaoMaoToken 文档

图片分析(本地)

本页介绍如何使用 OpenAI Responses API 分析本地图片。核心做法是先把本地图片编码为 Base64 Data URI,再通过 input_image 传给模型。

概述

本地图片分析适合无法提供公网图片 URL 的场景,例如本地截图、票据照片、产品图片、桌面文件等。

常见支持格式包括:

  • JPG / JPEG
  • PNG
  • GIF
  • WebP

请求地址

https://api.maomaotoken.com/v1/responses

实现步骤

  1. 读取图片从本地路径读取图片二进制内容。
  2. Base64 编码将图片转换为 data:image/...;base64 格式。
  3. 提交分析把文本提示和图片数据一起放入 input 数组发送给 Responses API。

Python 示例代码

下面示例会读取本地图片,将其转换为 Base64 Data URI,然后调用 MaomaoToken 进行图片内容识别。

"""
MaomaoToken 本地图片识别示例

功能:
将本地图片编码为 Base64 Data URI,
然后发送到 Responses API 进行图片内容分析。
"""

import base64
import json
import os
import requests


# ==================== 配置参数 ====================

API_KEY = "sk-****************************"
IMAGE_PATH = "test/example.jpg"
API_URL = "https://api.maomaotoken.com/v1/responses"


# ==================== 图片编码函数 ====================

def encode_image_to_base64(filepath: str) -> str:
    ext = os.path.splitext(filepath)[1].lower()

    mime_map = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".webp": "image/webp",
    }

    mime_type = mime_map.get(ext, "application/octet-stream")

    with open(filepath, "rb") as f:
        encoded = base64.b64encode(f.read()).decode("utf-8")

    return f"data:{mime_type};base64,{encoded}"


def extract_output_text(result: dict) -> str:
    output = result.get("output", [])

    for item in output:
        if item.get("type") != "message":
            continue

        content = item.get("content", [])
        if not isinstance(content, list):
            continue

        for content_item in content:
            if content_item.get("type") == "output_text":
                return content_item.get("text", "")

    return ""


# ==================== 主程序 ====================

if __name__ == "__main__":
    print("=" * 60)
    print("MaomaoToken 图片识别示例程序")
    print("=" * 60)

    print("[步骤 1/3] 正在编码图片...")
    image_data = encode_image_to_base64(IMAGE_PATH)
    print(f"编码成功,数据长度: {len(image_data)} 字符")

    print("[步骤 2/3] 正在构造 API 请求...")
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}",
    }

    payload = {
        "model": "gpt-5-mini",
        "input": [
            {
                "role": "user",
                "content": [
                    {"type": "input_text", "text": "描述这张图片"},
                    {"type": "input_image", "image_url": image_data},
                ],
            }
        ],
    }

    print("[步骤 3/3] 正在发送请求...")

    try:
        response = requests.post(API_URL, headers=headers, json=payload)
        response.raise_for_status()

        result = response.json()

        print("\n" + "=" * 60)
        print("完整 API 响应:")
        print("=" * 60)
        print(json.dumps(result, indent=2, ensure_ascii=False))

        description = extract_output_text(result)

        if description:
            print("\n" + "=" * 60)
            print("图片识别结果")
            print("=" * 60)
            print(description)
        else:
            print("未能从响应中提取图片描述,请检查完整响应结构。")

    except requests.exceptions.RequestException as e:
        print(f"网络请求失败: {e}")
    except json.JSONDecodeError as e:
        print(f"JSON 解析失败: {e}")
    except FileNotFoundError:
        print(f"图片文件不存在: {IMAGE_PATH}")
    except Exception as e:
        print(f"未知错误: {e}")

返回示例

成功运行后,你会看到执行进度、完整 API 响应,以及模型提取出的图片描述。

============================================================
MaomaoToken 图片识别示例程序
============================================================
[步骤 1/3] 正在编码图片...
编码成功,数据长度: 289823 字符
[步骤 2/3] 正在构造 API 请求...
[步骤 3/3] 正在发送请求...

============================================================
图片识别结果
============================================================
这是一张桌面拍摄的照片,画面正中是一台 Canon 品牌的台式计算器。计算器有大尺寸液晶显示屏、数字按键、运算按键和功能键。计算器放在带有纹理图案的桌垫上,周围还能看到毛巾和数据线等物品。整体光线充足,主体清晰。

响应结构示例

{
  "id": "resp_example",
  "object": "response",
  "model": "gpt-5-mini",
  "usage": {
    "total_tokens": 1324,
    "input_tokens": 933,
    "output_tokens": 391
  },
  "created_at": 1762518901,
  "status": "completed",
  "output": [
    {
      "id": "rs_example",
      "type": "reasoning",
      "summary": []
    },
    {
      "id": "msg_example",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "text": "这是一张桌面拍摄的照片,画面正中是一台 Canon 品牌的台式计算器。"
        }
      ],
      "role": "assistant"
    }
  ]
}

注意事项

  • 请将示例中的 sk-**************************** 替换为你的真实 API Key。
  • IMAGE_PATH 需要改成你的本地图片路径。
  • 图片体积越大,请求体越大,可能会影响速度和 Token 消耗。
  • 建议对超大图片先压缩或缩放,再发送给模型分析。
  • 图片内容识别结果由模型生成,仅供参考;涉及重要信息时建议人工复核。

On this page