OCR captcha solver for Node.js — extract text from CAPTCHA images with Tesseract.js + Jimp. Auto-preprocessing (grayscale, binarize, invert, upscale, pad), multi-pass fallback, character whitelisting. Supports Buffer, URL, Base64 & Axios responses.
It handles the messy parts for you: mixed image formats, dark/inverted backgrounds, noisy strokes, missing quiet zones, and edge-cut characters. Just pass in an image (Buffer, URL, Base64, or Axios response) and get clean text back.
- 🔍 Automatic image format detection — PNG, JPEG, GIF, WEBP, BMP (and rejects HTML error pages).
- 🧠 Smart preprocessing pipeline with Jimp:
- Grayscale conversion
- Contrast enhancement
- Auto-inversion for dark backgrounds
- Luminance binarization (thresholding)
- Image upscaling (2.5× by default — Tesseract loves big letters)
- Quiet-zone border padding
- ♻️ Multi-pass OCR fallback — tries multiple Tesseract PSM modes and the raw image if preprocessing fails.
- 🎯 Character whitelisting — restrict the alphabet for numeric-only or alphanumeric CAPTCHAs.
- 🧾 Flexible input handling — Buffer, ArrayBuffer, Base64 data URL, raw binary string, HTTP(S) URL, or a full Axios response.
- 🔧 Flexible function signatures — simple call or fine-grained options object.
- 🐛 Debug logging built-in for troubleshooting low-confidence OCR results.
npm install tesseract.js axios jimpNote:
tesseract.jsdownloads language data (~10 MB foreng) on first use. Ensure your environment has internet access, or configure a locallangPathin Tesseract.
const { detectCaptcha } = require('./captcha-ocr');
// From an Axios response
const axios = require('axios');
const res = await axios.get('https://example.com/captcha.png', {
responseType: 'arraybuffer'
});
const text = await detectCaptcha(res);
console.log('CAPTCHA text:', text);That's it. The module handles normalization, preprocessing, OCR, and cleanup.
Runs the full OCR pipeline and returns the extracted CAPTCHA text.
Parameters
| Name | Type | Description |
|---|---|---|
imageData |
Buffer | ArrayBuffer | string | Object |
The image. Accepts Buffer, URL, Base64 data URL, binary string, or Axios response. |
expectedLengthOrOptions |
number | string | Object |
Optional. Either the expected character count, a whitelist string, or an options object. |
charWhitelist |
string |
Optional. Characters Tesseract is allowed to return. |
options |
Object |
Optional. Tuning options (see below). |
Returns: Promise<string> — the cleaned, whitelisted text.
Runs the Jimp preprocessing pipeline independently. Useful if you want to inspect or cache preprocessed images.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
buffer |
Buffer |
— | Original image buffer. |
options.scale |
number |
2.5 |
Upscaling factor. |
options.contrast |
number |
0.4 |
Contrast boost (−1 to 1). |
options.threshold |
number | null |
140 |
Binarization cutoff (0–255). Set to null to disable. |
options.autoInvert |
boolean |
true |
Invert dark backgrounds automatically. |
options.padding |
number |
16 |
Quiet-zone padding in pixels. |
options.debug |
boolean |
false |
Enable log output. |
Returns: Promise<Buffer> — preprocessed PNG buffer.
The default allowed-character set:
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'| Option | Type | Default | Description |
|---|---|---|---|
expectedLength |
number |
null |
Expected number of characters (used for validation logging only). |
charWhitelist |
string |
DEFAULT_WHITELIST |
Allowed characters. |
preprocess |
boolean |
true |
Enable the Jimp preprocessing pipeline. |
psm |
string |
'8' |
Tesseract page-segmentation mode. 8 = single word, 7 = single line, 6 = uniform block, 13 = raw line. |
scale |
number |
2.5 |
Image upscaling factor. |
contrast |
number |
0.4 |
Contrast boost. |
threshold |
number |
140 |
Binarization cutoff (0–255). null disables. |
autoInvert |
boolean |
true |
Auto-invert dark backgrounds. |
padding |
number |
16 |
White quiet-zone padding (px). |
debug |
boolean |
true |
Print pipeline logs. |
const text = await detectCaptcha(imageBuffer);const text = await detectCaptcha(imageBuffer, 5);const text = await detectCaptcha(imageBuffer, 5, '0123456789');const text = await detectCaptcha(imageBuffer, {
expectedLength: 6,
charWhitelist: '0123456789',
psm: '7',
scale: 3,
contrast: 0.6,
threshold: 150,
autoInvert: true,
padding: 20,
debug: true
});const text = await detectCaptcha('https://example.com/api/captcha?id=123');const text = await detectCaptcha('data:image/png;base64,iVBORw0KG...');const res = await axios.get('https://example.com/captcha.png', {
responseType: 'arraybuffer'
});
const text = await detectCaptcha(res); // The whole response worksconst { preprocessCaptcha } = require('./captcha-ocr');
const cleanPng = await preprocessCaptcha(rawBuffer, {
scale: 3,
threshold: 128
});
require('fs').writeFileSync('debug.png', cleanPng);async function solveWithRetry(maxAttempts = 5) {
for (let i = 1; i <= maxAttempts; i++) {
const res = await axios.get('https://example.com/captcha', {
responseType: 'arraybuffer'
});
const text = await detectCaptcha(res, {
expectedLength: 5,
charWhitelist: '0123456789',
debug: i === maxAttempts // only log on the last attempt
});
if (text.length === 5) return text;
console.warn(`Attempt ${i} yielded "${text}", retrying...`);
}
throw new Error('Unable to solve CAPTCHA after retries');
}When you call detectCaptcha, the module runs this pipeline:
Input (Buffer | URL | Base64 | Axios response | ArrayBuffer)
│
▼
┌───────────────────────────────────────┐
│ 1. normalizeInput() │ → converts everything to Buffer
├───────────────────────────────────────┤
│ 2. inspectImageBuffer() │ → magic-byte format check
│ │ (rejects HTML error pages)
├───────────────────────────────────────┤
│ 3. Jimp preprocessing (optional) │
│ • Greyscale │
│ • Contrast boost │
│ • Auto-invert dark backgrounds │
│ • Binarize (threshold) │
│ • Upscale (default 2.5×) │
│ • Add white border padding │
├───────────────────────────────────────┤
│ 4. Tesseract OCR — Pass 1 │ → whitelist + configured PSM
│ If empty → Pass 2 (PSM 7) │
│ If empty → Pass 3 (raw buffer) │
├───────────────────────────────────────┤
│ 5. Post-filter with whitelist regex │ → strips invalid characters
└───────────────────────────────────────┘
│
▼
Clean text string
Different CAPTCHA providers behave differently. Try these tweaks if accuracy is low:
| Symptom | Suggested adjustment |
|---|---|
| Characters are cut off at edges | Increase padding (e.g., 24). |
| Text is too small | Increase scale (e.g., 3.5). |
| Background is noisy / patterned | Lower threshold (e.g., 120) or disable with null. |
| Strokes are broken | Raise contrast (e.g., 0.6). |
| Dark background not being inverted | Enable debug: true and check luminance log. |
| Multi-line text misread | Try psm: '6' (uniform block). |
| Numeric CAPTCHA misreads letters | Set charWhitelist: '0123456789'. |
| OCR returns nothing on clean images | Disable preprocessing with preprocess: false. |
Your HTTP request returned a webpage (e.g., a 403/404 error page) instead of image bytes.
Fix: Ensure Axios uses responseType: 'arraybuffer'.
axios.get(url, { responseType: 'arraybuffer' }); // ✅The server returned nothing. Common causes:
- Missing/incorrect
User-Agentheader - Missing session cookie or referer
- Server-side rate limiting or IP block
You passed something the module can't normalize (e.g., a plain object, undefined, a stream).
Fix: Convert to a Buffer first, or pass the URL / Axios response directly.
- Check whether preprocessing helped — try
preprocess: falseto compare. - Save the preprocessed image with
preprocessCaptcha()and inspect it visually. - Adjust
scale,threshold, orcontrastas shown in the tuning table.
If you're in an offline/restricted environment, configure Tesseract with a local langPath by patching the createWorker call in your fork, or copy eng.traineddata into the working directory.
const {
detectCaptcha,
preprocessCaptcha,
DEFAULT_WHITELIST
} = require('./captcha-ocr');| Export | Type | Purpose |
|---|---|---|
detectCaptcha |
async function |
Main OCR entry point. |
preprocessCaptcha |
async function |
Standalone Jimp preprocessing. |
DEFAULT_WHITELIST |
string |
Default allowed character set. |
- Node.js ≥ 20
- tesseract.js (installs its own WASM worker)
- jimp (v1.x or v2.x — both supported)
- axios (for URL input; not required if you only pass Buffers)
MIT — use it, modify it, ship it. Attribution appreciated but not required.
Found a CAPTCHA style that doesn't work well? Open an issue with:
- A sample (redacted/anonymized) image.
- The debug output from
detectCaptcha. - What you tried (
psm,threshold,scale, etc.).
PRs that improve accuracy, add preprocessing options, or broaden input handling are welcome.