Skip to content
# tuiOcrParse

OCR 文字识别 API — 调用设备端 OCR 引擎识别图片中的文字,返回识别文本与定位块数据。

介绍 ​

tuiOcrParse 是 uni-app x 环境下的 OCR 文字识别能力封装,通过 @/uni_modules/tui-ocr 导入调用。

适用于拍照识别、扫描文档、提取图片文字等场景。

导入 ​

ts
import { tuiOcrParse, type TuiOcrResult } from '@/uni_modules/tui-ocr'

基础用法 ​

ts
tuiOcrParse({
  path: imagePath,
  langs: 'zh',
  success: (res) => {
    console.log('识别文本:', res.texts)
    console.log('定位块:', res.textBlocks)
  },
  fail: (err) => {
    console.error('识别失败:', err.errMsg)
  },
  complete: () => {
    console.log('识别完成')
  }
})

API ​

调用参数 ​

参数名说明类型默认值
path本地图片路径String—
langs识别语言String'zh'
success识别成功回调(res: TuiOcrResult) => void—
fail识别失败回调(err: { errMsg: string }) => void—
complete完成回调(不论成功失败)() => void—

返回结果 (TuiOcrResult) ​

属性名说明类型
texts按行识别的文本数组String[]
textBlocks文本定位块原始数据(JSON 字符串数组)String[]

textBlocks 定位块数据格式 ​

每个定位块为 JSON 字符串,包含:

{
  "box": [[x1,y1],[x2,y2],[x3,y3],[x4,y4]], // 四角坐标
  "text": "识别文本",
  "confidence": 0.95,    // 置信度
  "angle": 0             // 旋转角度
}

完整示例 ​

参考 demo:demo/ocr/ocr.uvue

ts
function startRecognize() {
  loading.value = true
  tuiOcrParse({
    path: imagePath.value,
    langs: 'zh',
    success: (res) => {
      if (res.texts.length == 0) {
        // 未提取到文本
        return
      }
      // 合并全文
      const fullText = res.texts.join('\n')
      console.log('识别结果:', fullText)
    },
    fail: (err) => {
      console.error(err.errMsg)
    },
    complete: () => {
      loading.value = false
    }
  })
}

注意事项 ​

  • 仅支持 App 端(#ifdef APP)
  • 需确保设备具有 OCR 识别能力
  • path 需为本地图片路径,建议通过 uni.chooseImage 获取
  • 定位块数据 textBlocks 为原始识别引擎输出,格式可能随设备型号变化