图片识别 (OCR)OCR — Optical Character Recognition

高精度 AI 光学字符识别,支持中、英、日、韩等 50+ 语言。精准提取图片中的文字内容,支持表格识别、版面分析、印章检测等高级能力。High-accuracy AI-powered OCR supporting 50+ languages. Extract text from images with table recognition, layout analysis, seal detection, and more advanced features.

快速概览
端点EndpointPOST /v1/ocr
认证方式AuthBearer Token
输入方式Input文件上传 (multipart) 或 Base64 编码File upload (multipart) or Base64 encoded string
图片上限Max Size10 MB
输出模式Output Mode纯文本 / 分块含坐标 / 表格结构化 / 全版面分析Plain text / Blocks with coordinates / Table structured / Full layout
支持语言Languages50+ 语言,含中/英/日/韩/法/德/西等主流语言50+ languages including ZH/EN/JA/KO/FR/DE/ES and more

请求端点

Endpoint

POST/v1/ocr

认证

Authentication

Authorization: Bearer {access_token}

请求头

Request Headers

请求头Header必填Required说明Description
AuthorizationrequiredBearer 认证,格式:Bearer {access_token}Bearer authentication, format: Bearer {access_token}
Content-Typerequired文件上传时使用 multipart/form-data;Base64 模式使用 application/jsonUse multipart/form-data for file upload; application/json for Base64 mode

请求参数

Request Parameters

参数Parameter类型Type必填Required说明Description
imagefile / stringrequired图片文件 (multipart, ≤10MB) 或 Base64 编码字符串 (JSON)。建议分辨率 ≥ 200 DPI。Image file (multipart, ≤10MB) or Base64 encoded string (JSON). Recommended ≥ 200 DPI.
langstringoptional识别语言代码,默认 auto 自动检测。当已知语言时建议显式指定以提高准确度。多语言场景可用逗号分隔,如 zh,enLanguage code; default auto. Specify when known to improve accuracy. Use comma separation for multi-language: zh,en.
preserve_layoutbooleanoptional是否保留文本排版结构(段落、换行、缩进),默认 falsePreserve text layout (paragraphs, line breaks, indentation), default false
detect_tablesbooleanoptional是否识别表格并返回结构化数据(含行/列/单元格坐标),默认 falseDetect tables and return structured data (rows, columns, cell coordinates), default false
output_formatstringoptional输出格式:json(默认,完整结构化)、text(纯文本)、markdown(含表格 Markdown)、csv(仅表格时导出 CSV)Output format: json (default, full structured), text (plain), markdown (with Markdown tables), csv (CSV for tables only)
rotate_autobooleanoptional是否自动检测并纠正图片方向。默认 true,适用于拍摄角度不正的照片Auto-detect and correct image orientation. Default true, useful for tilted photos
enhance_contrastbooleanoptional是否增强图像对比度(低光照/模糊图片推荐开启)。默认 falseEnhance image contrast (recommended for low-light/blurry images). Default false
detect_orientationbooleanoptional是否检测文字方向(横排/竖排)。默认 true,对中日文竖排排版尤为关键Detect text orientation (horizontal/vertical). Default true, especially important for vertical CJK text
detect_languagebooleanoptional是否自动检测每段文字的语言(多语言混合图片)。默认 falseAuto-detect language per text block (for multi-language images). Default false
return_confidencebooleanoptional是否返回每个识别块的置信度评分。默认 trueReturn confidence score for each recognized block. Default true
max_regionsintegeroptional最大返回区域数,范围 1–500,默认 100。超过此数量时按置信度截断Max number of regions to return, range 1–500, default 100. Truncated by confidence if exceeded
detect_sealsbooleanoptional是否识别公章/印章中的文字,默认 falseDetect text in official seals/stamps, default false
detect_handwritingbooleanoptional是否启用高精度手写体识别,默认 false。开启后对手写笔记、签名有更好的识别效果Enable high-accuracy handwriting recognition, default false. Better for handwritten notes and signatures

支持图片格式

Supported Image Formats

格式FormatMIME 类型MIME Type说明Notes
JPEG / JPGimage/jpeg最常用格式,拍照识别首选Most common, preferred for photo-based OCR
PNGimage/png无损压缩,截图和合成图推荐Lossless compression, recommended for screenshots & composites
WebPimage/webp高压缩比,文件体积小High compression ratio, smaller files
BMPimage/bmp无压缩位图,保留最大细节Uncompressed bitmap, preserves maximum detail
TIFFimage/tiff扫描件常用,支持多页(仅处理第一页)Common for scanned documents, multi-page (first page only)

请求示例

Request Examples

cURL — 基础识别(文件上传)

cURL — Basic Recognition (File Upload)

curl -X POST https://api.itranslator.cc/v1/ocr \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -F "image=@invoice.jpg" \
  -F "lang=auto" \
  -F "preserve_layout=true"

cURL — 高级识别(含表格+印章+竖排文字)

cURL — Advanced (Table + Seal + Vertical Text)

curl -X POST https://api.itranslator.cc/v1/ocr \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -F "image=@contract.jpg" \
  -F "lang=zh,en" \
  -F "detect_tables=true" \
  -F "detect_seals=true" \
  -F "detect_orientation=true" \
  -F "output_format=json" \
  -F "return_confidence=true"

cURL — Base64 模式

cURL — Base64 Mode

curl -X POST https://api.itranslator.cc/v1/ocr \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "/9j/4AAQSkZJRgABAQAAAQABAAD...",
    "lang": "en",
    "output_format": "text"
  }'

Python — 文件上传

Python — File Upload

import requests

with open("invoice.jpg", "rb") as img:
    resp = requests.post(
        "https://api.itranslator.cc/v1/ocr",
        headers={"Authorization": f"Bearer {token}"},
        files={"image": img},
        data={
            "lang": "auto",
            "preserve_layout": True,
            "detect_tables": True,
            "output_format": "json"
        }
    )

result = resp.json()
print("识别文本:", result["text"])
for block in result.get("blocks", []):
    print(f"  [{block['type']}] {block['text']} (置信度: {block.get('confidence', 'N/A')})")

JavaScript (Node.js)

JavaScript (Node.js)

const fs = require("fs");

const form = new FormData();
form.append("image", fs.createReadStream("./scan.png"));
form.append("lang", "zh");
form.append("detect_tables", "true");
form.append("preserve_layout", "true");

const resp = await fetch("https://api.itranslator.cc/v1/ocr", {
  method: "POST",
  headers: { Authorization: `Bearer ${token}` },
  body: form
});
const data = await resp.json();
console.log(JSON.stringify(data, null, 2));

Java

Java

import java.net.URI;
import java.net.http.*;
import java.nio.file.*;

HttpClient client = HttpClient.newHttpClient();
byte[] imgBytes = Files.readAllBytes(Path.of("invoice.jpg"));
String base64 = java.util.Base64.getEncoder()
    .encodeToString(imgBytes);

String json = String.format(
  "{\"image\":\"%s\",\"lang\":\"auto\",\"preserve_layout\":true}",
  base64);

HttpRequest req = HttpRequest.newBuilder()
  .uri(URI.create("https://api.itranslator.cc/v1/ocr"))
  .header("Authorization", "Bearer " + token)
  .header("Content-Type", "application/json")
  .POST(HttpRequest.BodyPublishers.ofString(json))
  .build();

HttpResponse<String> resp = client.send(req,
  HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());

Go

Go

package main

import (
  "bytes"
  "encoding/json"
  "fmt"
  "io"
  "mime/multipart"
  "net/http"
  "os"
)

func main() {
  var buf bytes.Buffer
  w := multipart.NewWriter(&buf)

  file, _ := os.Open("invoice.jpg")
  defer file.Close()

  fw, _ := w.CreateFormFile("image", "invoice.jpg")
  io.Copy(fw, file)
  w.WriteField("lang", "auto")
  w.WriteField("preserve_layout", "true")
  w.Close()

  req, _ := http.NewRequest("POST",
    "https://api.itranslator.cc/v1/ocr", &buf)
  req.Header.Set("Authorization", "Bearer "+token)
  req.Header.Set("Content-Type", w.FormDataContentType())

  resp, _ := http.DefaultClient.Do(req)
  body, _ := io.ReadAll(resp.Body)
  fmt.Println(string(body))
}

响应字段说明

Response Fields

字段Field类型Type说明Description
textstring识别到的全部文本,按阅读顺序拼接All recognized text, concatenated in reading order
blocksarray文本块数组,每块含类型、文本、置信度、坐标 bboxText block array, each with type, text, confidence, and bbox coordinates
blocks[].typestring块类型:paragraph(段落)、line(单行)、word(单词)、table(表格)、seal(印章)、barcode(条码)Block type: paragraph, line, word, table, seal, barcode
blocks[].confidencefloat置信度 0–1,≥ 0.95 为高可信,0.80–0.95 建议人工复核Confidence 0–1; ≥ 0.95 high, 0.80–0.95 manual review recommended
blocks[].bboxarray[4]边界框 [x0, y0, x1, y1],左上/右下角像素坐标Bounding box [x0, y0, x1, y1], top-left/bottom-right pixel coordinates
blocks[].cellsarray表格单元格数组(仅 table 类型),含行/列索引及文本Table cell array (table only), with row/col index and text
langstring检测或指定的主要语言代码Detected or specified main language code
detected_langsarray检测到的所有语言列表(detect_language=true 时返回)All detected languages (returned when detect_language=true)
orientationstring文字方向:horizontal(横排)、vertical(竖排)Text orientation: horizontal, vertical
tablesarray结构化表格数组(仅 detect_tables=true),含行/列/单元格坐标Structured table array (only when detect_tables=true)
processing_time_msinteger处理耗时(毫秒)Processing time in milliseconds

响应示例

Response Examples

示例 1:纯文本模式 (output_format=text)

Example 1: Plain Text Mode (output_format=text)

{
  "text": "发票号码:12345678\n购买方:XX科技有限公司\n金额:¥1,000.00\n日期:2025年1月15日",
  "lang": "zh",
  "processing_time_ms": 120
}

示例 2:完整 JSON 模式(含分块坐标)

Example 2: Full JSON Mode (with block coordinates)

{
  "text": "发票号码:12345678\n购买方:XX科技有限公司\n金额:¥1,000.00",
  "blocks": [
    {
      "type": "paragraph",
      "text": "发票号码:12345678",
      "confidence": 0.98,
      "bbox": [10, 20, 200, 40]
    },
    {
      "type": "paragraph",
      "text": "购买方:XX科技有限公司",
      "confidence": 0.99,
      "bbox": [10, 50, 280, 70]
    },
    {
      "type": "paragraph",
      "text": "金额:¥1,000.00",
      "confidence": 0.97,
      "bbox": [10, 80, 200, 100]
    }
  ],
  "lang": "zh",
  "orientation": "horizontal",
  "processing_time_ms": 240
}

示例 3:表格识别 (detect_tables=true)

Example 3: Table Detection (detect_tables=true)

{
  "text": "姓名\t年龄\t城市\n张三\t28\t北京\n李四\t35\t上海\n王五\t42\t深圳",
  "blocks": [
    {
      "type": "table",
      "text": "姓名 年龄 城市\n张三 28 北京\n李四 35 上海\n王五 42 深圳",
      "confidence": 0.99,
      "bbox": [20, 30, 400, 150],
      "cells": [
        { "row": 0, "col": 0, "text": "姓名", "bbox": [20, 30, 120, 55] },
        { "row": 0, "col": 1, "text": "年龄", "bbox": [120, 30, 200, 55] },
        { "row": 0, "col": 2, "text": "城市", "bbox": [200, 30, 400, 55] },
        { "row": 1, "col": 0, "text": "张三", "bbox": [20, 55, 120, 80] },
        { "row": 1, "col": 1, "text": "28", "bbox": [120, 55, 200, 80] },
        { "row": 1, "col": 2, "text": "北京", "bbox": [200, 55, 400, 80] }
      ]
    }
  ],
  "tables": [
    {
      "rows": 4,
      "cols": 3,
      "headers": ["姓名", "年龄", "城市"],
      "data": [
        ["张三", "28", "北京"],
        ["李四", "35", "上海"],
        ["王五", "42", "深圳"]
      ]
    }
  ],
  "lang": "zh",
  "orientation": "horizontal",
  "processing_time_ms": 410
}

示例 4:竖排中日文 (detect_orientation=true)

Example 4: Vertical CJK Text (detect_orientation=true)

{
  "text": "春眠不覚暁 処処聞啼鳥 夜来風雨声 花落知多少",
  "blocks": [
    {
      "type": "paragraph",
      "text": "春眠不覚暁",
      "confidence": 0.96,
      "bbox": [120, 30, 145, 180]
    },
    {
      "type": "paragraph",
      "text": "処処聞啼鳥",
      "confidence": 0.95,
      "bbox": [160, 30, 185, 180]
    }
  ],
  "lang": "ja",
  "orientation": "vertical",
  "processing_time_ms": 280
}

置信度解读

Confidence Interpretation

置信度范围Range评级Rating建议处理方式Recommended Action
≥ 0.95★★★★★高可信,可直接使用Highly reliable, use directly
0.90 – 0.95★★★★较可信,建议抽查Reliable, spot-check recommended
0.80 – 0.90★★★中等,建议人工复核Moderate, manual review advised
0.60 – 0.80★★较低,必须人工校正Low, manual correction required
< 0.60不可用,建议更换图片或调整参数后重试Unreliable, retry with better image or adjusted parameters

错误码

Error Codes

状态码Status错误码Code说明Description
400INVALID_IMAGE图片格式不支持或已损坏Unsupported or corrupted image format
400IMAGE_TOO_LARGE图片超过 10MB 上限Image exceeds 10MB limit
400INVALID_BASE64Base64 编码无效或格式错误Invalid or malformed Base64 encoding
400INVALID_LANGUAGE不支持的语言代码Unsupported language code
400TOO_MANY_REGIONS图片内容过于复杂(文字区域过多),建议提高 max_regions 或裁剪图片Image too complex (too many text regions); increase max_regions or crop image
401UNAUTHORIZED缺少或无效的 Access TokenMissing or invalid access token
403FORBIDDEN无权访问该资源或配额已耗尽Access denied or quota exceeded
413PAYLOAD_TOO_LARGE请求体超过服务器限制Request body too large
422NO_TEXT_DETECTED图片中未检测到文字。尝试开启 enhance_contrast 或检查图片是否包含文字No text detected. Try enable_contrast or verify image contains text
429RATE_LIMITED请求频率超限,请降低并发数Rate limit exceeded, reduce concurrency
500INTERNAL_ERROR服务器内部错误,请稍后重试Internal server error, try again later
503SERVICE_UNAVAILABLE服务暂时不可用,请稍后重试Service temporarily unavailable

最佳实践

Best Practices

  1. 选择合适的图片:保证图片清晰、光照均匀。文字区域在图片中占比越大,识别准确率越高。
  2. Choose Good Images: Ensure images are clear with even lighting. Larger text regions yield higher accuracy.
  3. 预处理低质量图片:对于低光照、模糊或倾斜的图片,开启 enhance_contrast=truerotate_auto=true 来改善识别效果。
  4. Preprocess Low-Quality Images: Enable enhance_contrast=true and rotate_auto=true for low-light, blurry, or tilted images.
  5. 指定语言提高准确度:尽量显式指定 lang 参数而非使用 auto。对多语言混合图片使用逗号分隔,如 zh,en
  6. Specify Language: Explicitly set lang instead of auto when possible. Use comma separation like zh,en for multilingual images.
  7. 竖排文字处理:中日文竖排文献(如古籍、海报),务必开启 detect_orientation=true,否则按横排识别结果可能完全错误。
  8. Vertical Text: For vertical CJK documents (ancient texts, posters), always enable detect_orientation=true or results may be entirely wrong.
  9. 大图裁剪:如果只关心图片中特定区域的文字,建议先裁剪目标区域后再调用 OCR,减少不必要的识别开销。
  10. Crop Large Images: If only a specific region matters, crop before calling OCR to reduce unnecessary processing.
  11. 错误重试:对于 429(频率限制)和 5xx(服务器错误),建议实现指数退避重试策略。
  12. Retry Strategy: Implement exponential backoff for 429 (rate limit) and 5xx (server errors).

常见应用场景

Common Use Cases

场景Scenario推荐参数组合Recommended Parameters
发票/票据识别Invoice & Receiptpreserve_layout=true, detect_tables=true
合同/文档数字化Contract Digitizationpreserve_layout=true, detect_seals=true, enhance_contrast=true
证件信息提取ID/Document Extractionlang=zh, return_confidence=true
表格数据录入Table Data Entrydetect_tables=true, output_format=markdown
名片管理Business Cardpreserve_layout=true, detect_language=true
手写笔记Handwritten Notesdetect_handwriting=true, enhance_contrast=true
古籍/竖排文献Ancient/Vertical Textdetect_orientation=true, lang=zh
多语言菜单/海报Multilingual Menus/Postersdetect_language=true, lang=auto

OCR 能力模式对比

OCR Capability Comparison

能力Capability标准模式Standard Mode高级模式Advanced Mode
基础文字识别Basic Text
多语言文字Multi-language
版面分析Layout Analysis preserve_layout
表格识别Table Detection detect_tables
竖排文字Vertical Text detect_orientation
印章识别Seal Detection detect_seals
手写体识别Handwriting detect_handwriting
条码/二维码Barcode/QR 自动检测

输出格式说明

Output Formats

格式FormatContent-TypeContent-Type适用场景Use Case
jsonapplication/json默认,返回完整结构化数据(文本 + 坐标 + 置信度 + 表格)Default, full structured data (text + coordinates + confidence + tables)
texttext/plain仅返回纯文本,适合直接入库或简单展示Plain text only, suitable for direct storage or simple display
markdownapplication/jsonJSON 包装,但 text 字段为 Markdown 格式,表格自动转为 Markdown 表格JSON-wrapped but text in Markdown, tables auto-converted to Markdown tables
csvtext/csv仅当检测到表格时有效,直接返回 CSV 格式数据Only valid when tables detected, returns CSV directly
使用说明
  • 文件上传使用 multipart/form-data 编码,Content-Type 请勿手动设置,让 HTTP 客户端自动生成。
  • Use multipart/form-data encoding; let the HTTP client auto-generate Content-Type.
  • Base64 模式适用于网络图片或无法直接上传文件的场景,注意 Base64 编码后的字符串会比原文件大约 33%。
  • Base64 mode is for network images or scenarios where file upload is unavailable. Note Base64 encoding increases size by ~33%.
  • 单次请求超时时间为 20 秒。复杂版面、大表格或开启多个高级检测能力时,处理时间会相应增加。
  • Request timeout is 20 seconds. Processing time increases with complex layouts, large tables, or multiple advanced detection features.
  • 请勿在客户端代码中暴露 Access Token,建议通过后端代理调用。
  • Do not expose your Access Token in client-side code; use a backend proxy.
  • 如需对识别结果进行翻译,请将 OCR 输出的 text 字段传入文本翻译 API,或直接使用图片翻译 API 一步完成。
  • To translate OCR results, pass the text field to the Text Translation API, or use Image Translation API for a one-step solution.