Package Exports
- wx-ocr
- wx-ocr/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (wx-ocr) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
wx-ocr
超简单的 Node.js OCR 库 - 一行代码识别图片文字
安装
npm install wx-ocr使用
基础用法
const { ocr } = require('wx-ocr');
ocr('image.png').then(result => {
console.log(result);
});只获取文本
const { ocr } = require('wx-ocr');
// 文本数组
ocr('image.png', { returnTextOnly: true }).then(texts => {
console.log(texts); // ['文本1', '文本2', ...]
});
// 格式化文本(带换行)
ocr('image.png', {
returnTextOnly: true,
formatText: true
}).then(text => {
console.log(text); // "文本1\n文本2\n..."
});async/await
const { ocr } = require('wx-ocr');
async function main() {
const result = await ocr('image.png');
console.log(result);
}
main();批量识别
const { ocrBatch } = require('wx-ocr');
ocrBatch(['img1.png', 'img2.png']).then(results => {
results.forEach((result, i) => {
console.log(`图片 ${i + 1}:`, result);
});
});Express 服务器
const express = require('express');
const { ocr } = require('wx-ocr');
const app = express();
app.post('/ocr', async (req, res) => {
try {
const result = await ocr(req.file.path);
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);API
ocr(imagePath, options)
识别图片中的文字
参数:
imagePath(string) - 图片路径options(object) - 可选配置returnTextOnly(boolean) - 只返回文本数组,默认 falseformatText(boolean) - 格式化文本(带换行),默认 false
返回: Promise
示例:
// 完整结果(包含位置信息)
const result = await ocr('image.png');
// {
// taskId: 1,
// ocrResult: [
// { text: 'Hello', location: { left: 10, top: 20, right: 100, bottom: 50 } }
// ]
// }
// 只要文本
const texts = await ocr('image.png', { returnTextOnly: true });
// ['Hello', 'World']
// 格式化文本
const formatted = await ocr('image.png', { returnTextOnly: true, formatText: true });
// "Hello\nWorld"ocrBatch(imagePaths, options)
批量识别多张图片
参数:
imagePaths(string[]) - 图片路径数组options(object) - 同ocr()
返回: Promise
CLI 命令行
# 识别单张图片
wx-ocr ocr image.png
# 只输出文本
wx-ocr ocr image.png --text-only
# 格式化文本
wx-ocr ocr image.png --text-only --format
# 批量识别
wx-ocr batch image1.png image2.pngTypeScript
完整的 TypeScript 类型定义:
import { ocr, ocrBatch, OcrResult } from 'wx-ocr';
const result: OcrResult = await ocr('image.png');
const texts: string[] = await ocr('image.png', { returnTextOnly: true });系统要求
- Windows 系统
- Node.js 14+
License
MIT