深度

Claude 多模态能力实战:用 Vision API 分析图片、截图转代码、OCR 提取

Claude Vision 多模态 API 完整实战:图片上传方式(base64/URL)、截图直接转 React 组件代码、OCR 文字提取、数据图表分析、设计稿审查、PDF 页面处理,以及 Claude Code 终端上传图片的完整工作流。

2026/3/154分钟 阅读ClaudeEagle

Claude 的 Vision(视觉)能力让它可以直接理解图片内容——分析截图、识别文字、理解图表、把设计稿转成代码。本文展示所有实用场景。

支持的图片格式

  • JPEG、PNG、GIF、WebP
  • 最大单张:5MB(base64)或 URL 引用
  • 每次请求最多 20 张图片

基础 API 用法

方式 1:本地图片(base64)

python
import anthropic, base64

client = anthropic.Anthropic()

with open('screenshot.png', 'rb') as f:
    image_data = base64.standard_b64encode(f.read()).decode('utf-8')

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/png",
                    "data": image_data
                }
            },
            {"type": "text", "text": "Describe what you see in this screenshot."}
        ]
    }]
)
print(response.content[0].text)

方式 2:URL 图片

python
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "url",
                    "url": "https://example.com/chart.png"
                }
            },
            {"type": "text", "text": "Analyze this chart and extract the key data points."}
        ]
    }]
)

场景 1:截图转 React 代码

python
def screenshot_to_react(image_path):
    with open(image_path, 'rb') as f:
        data = base64.standard_b64encode(f.read()).decode('utf-8')
    
    prompt = """
    Convert this UI screenshot to a React component.
    Requirements:
    - TypeScript
    - Tailwind CSS for styling
    - Match the layout and colors as closely as possible
    - Make it responsive (mobile-first)
    - Use semantic HTML
    Output only the component code.
    """
    
    response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=4096,
        messages=[{
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}},
                {"type": "text", "text": prompt}
            ]
        }]
    )
    return response.content[0].text

code = screenshot_to_react('figma-design.png')

场景 2:OCR 文字提取

python
def extract_text(image_path):
    with open(image_path, 'rb') as f:
        data = base64.standard_b64encode(f.read()).decode('utf-8')
    
    ext = image_path.split('.')[-1].lower()
    media_type = {'jpg': 'image/jpeg', 'jpeg': 'image/jpeg',
                  'png': 'image/png', 'webp': 'image/webp'}.get(ext, 'image/png')
    
    response = client.messages.create(
        model="claude-haiku-3-5",
        max_tokens=2048,
        messages=[{
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": data}},
                {"type": "text", "text": "Extract all text from this image. Preserve formatting (tables, lists). Output only the extracted text."}
            ]
        }]
    )
    return response.content[0].text

# 批量处理扫描文档
import glob
for img in glob.glob('scanned/*.png'):
    text = extract_text(img)
    with open(img.replace('.png', '.txt'), 'w') as f:
        f.write(text)

场景 3:数据图表分析

python
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {"type": "image", "source": {"type": "url", "url": chart_url}},
            {"type": "text", "text": """
Analyze this chart:
1. What type of chart is this?
2. Extract all data points as JSON
3. Identify the trend (increasing/decreasing/stable)
4. What's the highest and lowest value?
5. Key insight in one sentence
            """}
        ]
    }]
)

场景 4:设计稿审查

python
def review_design(design_img, spec_img=None):
    content = []
    with open(design_img, 'rb') as f:
        d = base64.standard_b64encode(f.read()).decode()
    content.append({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": d}})
    
    if spec_img:
        with open(spec_img, 'rb') as f:
            d2 = base64.standard_b64encode(f.read()).decode()
        content.append({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": d2}})
        content.append({"type": "text", "text": "First image is the implementation, second is the spec. Find differences."})
    else:
        content.append({"type": "text", "text": "Review this UI for: accessibility issues, spacing inconsistencies, color contrast, missing hover states."})
    
    response = client.messages.create(
        model="claude-sonnet-4-5", max_tokens=1024,
        messages=[{"role": "user", "content": content}]
    )
    return response.content[0].text

在 Claude Code 终端中使用图片

bash
# 在交互模式里直接粘贴截图
claude
# 然后 Ctrl+V 粘贴截图(macOS/Linux 支持)
# 或拖拽图片文件到终端

# 非交互模式
claude -p "Convert this design to React component" --image design.png

多图对比

python
# 对比两个版本的 UI
def compare_screenshots(before_path, after_path):
    images = []
    for path in [before_path, after_path]:
        with open(path, 'rb') as f:
            d = base64.standard_b64encode(f.read()).decode()
        images.append({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": d}})
    
    images.append({"type": "text", "text": "Compare these two screenshots. List all visual differences."})
    
    response = client.messages.create(
        model="claude-sonnet-4-5", max_tokens=1024,
        messages=[{"role": "user", "content": images}]
    )
    return response.content[0].text

来源:Vision API - Anthropic 官方文档

相关文章推荐

深度Claude Managed Agents 完整解读:把 Agent 基础设施完全托管给 AnthropicClaude Managed Agents官方文档详解:Agent/Environment/Session/Events四大核心概念、五步工作流程、适用场景(长时间运行任务/云端沙箱/自托管/定时执行)、内置工具清单、与Messages API对比选型,Beta阶段接入指南,Anthropic Agent基础设施托管服务完整解读。2026/8/25深度Claude 提示词工程官方最佳实践:黄金法则、Few-shot示例与 effort 参数完整解读Anthropic官方提示词工程最佳实践深度解读:新同事黄金法则、为规则附加因果理由提升泛化、3-5个Few-shot示例经验、XML标签结构化提示、长文档排版提升30%质量、预填充响应迁移方案、Opus 4.7 effort参数五档位与自适应思考完整指南。2026/8/23深度Codex CLI 0.150 前瞻:浏览器/电脑操作配置成型,AWS Bedrock 账号体系搭建中Codex CLI 0.150系列alpha预览版进展:浏览器与电脑操作配置体系逐步完善、AWS Bedrock企业账号接入指南详解(支持GPT-5.6系列新模型sol/terra/luna)、两种认证方式对比、config.toml完整配置示例,面向企业级云原生部署场景。2026/8/23深度Codex vs Claude Code 2026 深度对比:便宜10倍的异步自动化 vs 输出质量更受青睐的深度重构Codex与Claude Code 2026深度基准测试对比:SWE-bench Verified/Pro跑分差异解读、单任务成本对比($15 vs $155)、盲测代码质量评审Claude Code 67%时间更受偏好、1M token上下文与异步沙箱执行模型差异、定价阶梯与决策框架完整梳理。2026/8/22深度Codex CLI 0.147 深度解析:可移植 Agent Plugins、MCP 2026-07-28 协议、--approve-for-me 自动审批Codex CLI 0.147.0深度解析:可移植Agent Plugins支持本地/个人/团队/远程四层目录发现安装,MCP 2026-07-28协议新增分页发现和非阻塞启动,--approve-for-me自动审批工作流,策略失败拒绝网络访问安全加固,面向团队级agent治理。2026/8/20深度WorkBuddy 资料库大升级:从文件存储到 AI 原生知识空间,HTML/Markdown 变身"活页面"WorkBuddy 5.3.11版本资料库能力升级详解:从传统文件存储升级为AI原生知识管理空间,支持人机共同读写协同编辑,HTML成为能改能协作能发布能存数据的活页面,Markdown支持批注审阅协同,解读人机共创设计思路。2026/8/20