API Tutorials

How to Solve Image CAPTCHA with Base64 API

Image CAPTCHAs show distorted text or numbers that users must type to prove they are human. CaptchaAI supports solving these via two methods: file upload and base64 encoding. The base64 method is ideal when you already have the image in memory (from a screenshot, page scraping, or API response) and want to avoid writing temporary files.

Send the base64-encoded image to in.php with method=base64, and CaptchaAI returns the recognized text.


What you need

Requirement Details
CaptchaAI API key captchaai.com
CAPTCHA image JPG, PNG, or GIF, 100 bytes to 100 KB
Python 3.7+ or Node.js 18+ For the examples below

How base64 submission works

Instead of uploading a file, you:

  1. Capture the CAPTCHA image from the page
  2. Encode it as a base64 string
  3. Send it to CaptchaAI with method=base64 and body=<base64_string>
  4. Poll for the OCR result

This avoids disk I/O and works well in serverless environments or headless browser workflows where the image is already in memory.


Python implementation

Submit and solve

import requests
import base64
import time

API_KEY = "YOUR_API_KEY"


def solve_image_captcha_base64(image_path):
    """Solve an image CAPTCHA using base64 encoding."""

    # Read and encode the image
    with open(image_path, "rb") as f:
        image_base64 = base64.b64encode(f.read()).decode("utf-8")

    # Submit task with base64 body
    submit = requests.post("https://ocr.captchaai.com/in.php", data={
        "key": API_KEY,
        "method": "base64",
        "body": image_base64,
        "json": 1
    }).json()

    if submit.get("status") != 1:
        raise RuntimeError(f"Submit error: {submit.get('request')}")

    task_id = submit["request"]
    print(f"Task ID: {task_id}")

    # Poll for result
    time.sleep(5)
    for _ in range(20):
        result = requests.get("https://ocr.captchaai.com/res.php", params={
            "key": API_KEY, "action": "get", "id": task_id, "json": 1
        }).json()

        if result.get("status") == 1:
            return result["request"]
        if result.get("request") != "CAPCHA_NOT_READY":
            raise RuntimeError(f"Solve error: {result['request']}")
        time.sleep(5)

    raise TimeoutError("Solve timed out")


text = solve_image_captcha_base64("captcha.png")
print(f"Solved text: {text}")

From a URL (download + encode)

def solve_captcha_from_url(image_url):
    """Download a CAPTCHA image and solve it via base64."""
    image_data = requests.get(image_url).content
    image_base64 = base64.b64encode(image_data).decode("utf-8")

    submit = requests.post("https://ocr.captchaai.com/in.php", data={
        "key": API_KEY,
        "method": "base64",
        "body": image_base64,
        "json": 1
    }).json()

    if submit.get("status") != 1:
        raise RuntimeError(f"Submit error: {submit.get('request')}")

    task_id = submit["request"]

    time.sleep(5)
    for _ in range(20):
        result = requests.get("https://ocr.captchaai.com/res.php", params={
            "key": API_KEY, "action": "get", "id": task_id, "json": 1
        }).json()

        if result.get("status") == 1:
            return result["request"]
        if result.get("request") != "CAPCHA_NOT_READY":
            raise RuntimeError(f"Solve error: {result['request']}")
        time.sleep(5)

    raise TimeoutError("Solve timed out")

Node.js implementation

const fs = require("fs");

const API_KEY = "YOUR_API_KEY";

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function solveImageCaptchaBase64(imagePath) {
  // Read and encode the image
  const imageBuffer = fs.readFileSync(imagePath);
  const imageBase64 = imageBuffer.toString("base64");

  // Submit task
  const submitRes = await fetch("https://ocr.captchaai.com/in.php", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      key: API_KEY,
      method: "base64",
      body: imageBase64,
      json: "1",
    }),
  });
  const submitData = await submitRes.json();

  if (submitData.status !== 1) {
    throw new Error(`Submit error: ${submitData.request}`);
  }

  const taskId = submitData.request;
  console.log(`Task ID: ${taskId}`);

  // Poll for result
  await delay(5000);

  for (let i = 0; i < 20; i++) {
    const pollRes = await fetch(
      `https://ocr.captchaai.com/res.php?${new URLSearchParams({
        key: API_KEY,
        action: "get",
        id: taskId,
        json: "1",
      })}`
    );
    const pollData = await pollRes.json();

    if (pollData.status === 1) {
      return pollData.request;
    }

    if (pollData.request !== "CAPCHA_NOT_READY") {
      throw new Error(`Solve error: ${pollData.request}`);
    }

    await delay(5000);
  }

  throw new Error("Solve timed out");
}

(async () => {
  const text = await solveImageCaptchaBase64("captcha.png");
  console.log(`Solved text: ${text}`);
})();

Expected output:

Task ID: 73849562810
Solved text: ABC123

Optional parameters

Parameter Description Example
numeric 1 = digits only, 2 = letters only, 0 = any numeric=1
min_len Minimum text length min_len=4
max_len Maximum text length max_len=8
phrase 1 = contains spaces phrase=0
regsense 1 = case-sensitive regsense=1
language 0 = default, 1 = Cyrillic, 2 = Latin language=2

Example with parameters:

submit = requests.post("https://ocr.captchaai.com/in.php", data={
    "key": API_KEY,
    "method": "base64",
    "body": image_base64,
    "numeric": 1,      # digits only
    "min_len": 4,
    "max_len": 6,
    "json": 1
}).json()

Troubleshooting

Error Cause Fix
ERROR_ZERO_CAPTCHA_FILESIZE Image payload too small (<100 bytes) Ensure valid image data is being encoded
ERROR_TOO_BIG_CAPTCHA_FILESIZE Image exceeds 100 KB Compress or resize the image
ERROR_WRONG_FILE_EXTENSION Unsupported format Use JPG, PNG, or GIF
ERROR_IMAGE_TYPE_NOT_SUPPORTED Corrupt or unrecognized image Re-encode as standard PNG/JPG
Wrong text returned Low image quality Increase image resolution, reduce compression
Wrong text returned Missing hint parameters Add numeric, min_len, max_len as appropriate

FAQ

When should I use base64 vs file upload?

Use base64 when the image is already in memory (screenshots, API responses, headless browser captures). Use file upload when you have a CAPTCHA image saved on disk.

What image formats are supported?

JPG, JPEG, PNG, and GIF. Images must be between 100 bytes and 100 KB.

How fast are image CAPTCHA solves?

Typically 2–10 seconds, much faster than token-based CAPTCHAs like reCAPTCHA.

Can I solve math CAPTCHAs with this method?

Yes. CaptchaAI recognizes math expressions (e.g., "3 + 7 =") and returns the answer as text.

How do I improve accuracy?

Use the numeric, min_len, max_len, and language parameters to constrain the expected answer format. Higher-quality images also improve accuracy.


Start solving image CAPTCHAs

Get your API key at captchaai.com. Use method=base64 with your encoded image data.


Discussions (0)

No comments yet.

Related Posts

Tutorials Image CAPTCHA Confidence Scores: Using CaptchaAI Quality Metrics
how to use Captcha AI's confidence indicators for image CAPTCHA solutions — assess answer quality, implement confidence-based retry logic, and optimize solve ra...

Learn how to use Captcha AI's confidence indicators for image CAPTCHA solutions — assess answer quality, imple...

Automation Python Image OCR
Mar 30, 2026
API Tutorials Solve Image CAPTCHA with Python OCR and CaptchaAI
Solve distorted text image CAPTCHAs using Captcha AI's OCR API from Python.

Solve distorted text image CAPTCHAs using Captcha AI's OCR API from Python. Covers file upload, base 64 submis...

Automation Python Image OCR
Use Cases Government Portal Automation with CAPTCHA Solving
Automate government portal interactions (visa applications, permit filings, records requests) with Captcha AI handling CAPTCHA challenges.

Automate government portal interactions (visa applications, permit filings, records requests) with Captcha AI...

Automation Python reCAPTCHA v2
Jan 30, 2026
API Tutorials Batch Image CAPTCHA Solving: Processing 1000+ Images
Process thousands of image CAPTCHAs efficiently with Captcha AI using async queues, worker pools, and rate-aware batching in Python and Node.js.

Process thousands of image CAPTCHAs efficiently with Captcha AI using async queues, worker pools, and rate-awa...

Automation Python Image OCR
Mar 21, 2026
Tutorials CAPTCHA Solving Fallback Chains
Implement fallback chains for CAPTCHA solving with Captcha AI.

Implement fallback chains for CAPTCHA solving with Captcha AI. Cascade through solver methods, proxy pools, an...

Automation Python reCAPTCHA v2
Apr 06, 2026
API Tutorials CaptchaAI API Latency Optimization: Faster Solves
Reduce CAPTCHA solve latency with Captcha AI by optimizing poll intervals, connection pooling, prefetching, and proxy selection.

Reduce CAPTCHA solve latency with Captcha AI by optimizing poll intervals, connection pooling, prefetching, an...

Automation Python reCAPTCHA v2
Feb 27, 2026
API Tutorials Building a Python Wrapper Library for CaptchaAI API
Build a reusable Python wrapper library for the Captcha AI API with type hints, retry logic, context managers, and support for CAPTCHA types.

Build a reusable Python wrapper library for the Captcha AI API with type hints, retry logic, context managers,...

Automation Python reCAPTCHA v2
Jan 31, 2026
Troubleshooting Grid Image Coordinate Errors: Diagnosis and Fix
Fix grid image CAPTCHA coordinate errors when using Captcha AI.

Fix grid image CAPTCHA coordinate errors when using Captcha AI. Covers wrong grid size, cell numbering mismatc...

Automation Python Image OCR
Feb 26, 2026
Tutorials Python Multiprocessing for Parallel CAPTCHA Solving
Use Python multiprocessing to solve CAPTCHAs in parallel with Captcha AI.

Use Python multiprocessing to solve CAPTCHAs in parallel with Captcha AI. Process Pool Executor, Pool, and hyb...

Automation Python Image OCR
Apr 01, 2026
API Tutorials How to Solve reCAPTCHA v2 Callback Using API
how to solve re CAPTCHA v 2 callback implementations using Captcha AI API.

Learn how to solve re CAPTCHA v 2 callback implementations using Captcha AI API. Detect the callback function,...

Automation reCAPTCHA v2 Webhooks
Mar 01, 2026
API Tutorials Solve GeeTest v3 CAPTCHA with Python and CaptchaAI
Step-by-step Python tutorial for solving Gee Test v 3 slide puzzle CAPTCHAs using the Captcha AI API.

Step-by-step Python tutorial for solving Gee Test v 3 slide puzzle CAPTCHAs using the Captcha AI API. Includes...

Automation Python Testing
Mar 23, 2026
API Tutorials Case-Sensitive CAPTCHA API Parameter Guide
How to use the regsense parameter for case-sensitive CAPTCHA solving with Captcha AI.

How to use the regsense parameter for case-sensitive CAPTCHA solving with Captcha AI. Covers when to use, comm...

Python Web Scraping Image OCR
Apr 09, 2026