基于 Node.js 与 Tesseract.js 的验证码识别系统设计与实现

一、项目背景
验证码(CAPTCHA)广泛用于防止恶意行为,如刷票、注册机等。传统验证码识别依赖 Python 等语言,但前端开发者也可以使用 JavaScript 完成 OCR 工作。本文介绍如何使用 Node.js 与浏览器版 Tesseract.js 实现一套轻量级验证码识别系统。
更多内容访问ttocr.com或联系1436423940
二、技术栈选择
技术 用途
Node.js 后端运行环境
Tesseract.js OCR 识别库(Web 版本)
Express.js 提供简单 API 接口
Jimp 图像处理(灰度化、二值化)

三、项目环境准备

  1. 安装 Node.js
    官网下载安装:https://nodejs.org/

  2. 初始化项目并安装依赖

mkdir captcha-ocr-js
cd captcha-ocr-js
npm init -y

npm install express tesseract.js jimp multer
四、项目结构

captcha-ocr-js/
├── index.js # 主程序
├── uploads/ # 上传验证码的临时文件夹
└── package.json
五、核心代码实现

  1. index.js

const express = require('express');
const multer = require('multer');
const Jimp = require('jimp');
const Tesseract = require('tesseract.js');
const fs = require('fs');

const app = express();
const port = 3000;

const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('captcha'), async (req, res) => {
const imagePath = req.file.path;

// 加载并预处理图像
const image = await Jimp.read(imagePath);
image
    .grayscale()      // 灰度处理
    .contrast(1)      // 增强对比度
    .write(imagePath); // 覆盖保存

// OCR 识别
const { data: { text } } = await Tesseract.recognize(
    imagePath,
    'eng',
    {
        logger: m => console.log(m) // 可选:输出进度
    }
);

fs.unlinkSync(imagePath); // 删除临时文件
res.json({ result: text.trim() });

});

app.listen(port, () => {
console.log(验证码识别服务运行于 http://localhost:${port});
});
六、测试

  1. 启动服务

node index.js
2. 使用 curl 或 Postman 测试上传

curl -F "captcha=@./test.png" http://localhost:3000/upload
返回:

{
"result": "4Gk7"
}

posted @ 2025-07-19 13:09  ttocr、com  阅读(30)  评论(0)    收藏  举报