Image text removal API tutorial

Remove Text and Permitted Watermarks from Images via API

Use Python or server-side JavaScript to remove captions, labels, timestamps, annotations, and authorized watermarks. Save ready-to-use output and scale larger image collections with bounded concurrency.

PixLab 11 min read
Authorized source image containing text before TXT-REMOVE processing Before
Cleaned image after automatic text removal with the TXT-REMOVE API After
No mask or coordinates POST /txtremove

Text overlays are common in product photos, campaign graphics, screenshots, localized assets, and media archives. When your organization owns the image or has permission to modify it, the PixLab TXT-REMOVE API can locate captions, labels, timestamps, annotations, and permitted watermarks, then reconstruct the covered image area.

To test the workflow on authorized images, start the PixLab 7-day free trial and create an API key. Current limits and plan details are available in the Console.

Lawful-use requirement Only process content you own or have permission to modify. Do not remove copyright notices, branding, stock-photo watermarks, or other ownership marks from third-party content without authorization. Review the PixLab Terms of Service before deploying a watermark-removal workflow.

Overview

What You Will Build

By the end of this tutorial, you will be able to:

  • Upload an image to /txtremove with multipart/form-data.
  • Remove detected text-like overlays without preparing a mask or coordinate list.
  • Decode the default Base64 response and save the cleaned image.
  • Call TXT-REMOVE from server-side JavaScript without exposing your API key.
  • Request raw image bytes or use output stored in your AWS S3 bucket.
  • Process a collection through a bounded worker pool.
  • Choose between TXT-REMOVE and BG-REMOVE for the task at hand.

Before You Start

  1. 1A PixLab API key from the 7-day free trial in the PixLab Console.
  2. 2Python 3 with the requests package, or Node.js 18 or newer.
  3. 3One or more images that you own or are authorized to modify.
  4. 4The TXT-REMOVE API reference for complete parameter and response documentation.
Protect your credentialsStore the API key in an environment variable. Do not commit it to source control or expose it in public browser-side JavaScript.

How the Text-Removal Request Works

TXT-REMOVE uses one endpoint:

https://api.pixlab.io/txtremove

Send a synchronous POST request using multipart/form-data. Place the local source image in the file field and provide your API key in the form data.

TXT-REMOVE request values
ValuePurpose
fileThe local image to process.
keyYour PixLab API key.
blobOptional. Set to true to receive raw image bytes instead of JSON.

TXT-REMOVE detects text-like regions automatically and reconstructs them using surrounding colors, textures, gradients, and image structure. The result is a cleaned image, not a source image with text hidden behind a blur or solid rectangle.

By default, the endpoint returns JSON containing Base64-encoded image data. If you connect your own AWS S3 bucket, it can return a link to the result stored in that bucket instead.

Step 1

Start the Trial and Create an API Key

Open the PixLab Console, start the 7-day free trial, and create your API key. Keep the key on your backend and load it from an environment variable.

PowerShell

$env:PIXLAB_API_KEY="YOUR_API_KEY"

Bash or Zsh

export PIXLAB_API_KEY="YOUR_API_KEY"

The examples below read PIXLAB_API_KEY from the environment so the credential remains separate from the application source code.

Step 2

Choose Representative Input Images

Text-removal quality depends on the overlay and the image beneath it. Build a test set that represents the images your application will actually receive.

  • Include different text sizes, fonts, colors, and positions.
  • Test captions, timestamps, labels, annotations, and authorized overlays separately.
  • Include both simple backgrounds and detailed textures.
  • Review examples where text crosses faces, products, fine edges, or repeating patterns.
  • Avoid judging a production workflow from one carefully selected image.
Authorized source image containing text before TXT-REMOVE processingSource image
An authorized source image before its text overlay is submitted to TXT-REMOVE.
Cleaned image after automatic text removal with the TXT-REMOVE APICleaned output
The cleaned image returned after automatic text detection and reconstruction.

Large overlays, transparent marks, heavy compression, and text placed over faces or dense visual detail can be harder to reconstruct. Automated inpainting cannot recover every hidden pixel exactly, so route commercially important or difficult outputs through an appropriate review step.

Step 3

Remove Text from an Image with Python

Install the Python dependency:

python -m pip install requests

Create remove_image_text.py:

import base64
import os
from pathlib import Path

import requests

endpoint = "https://api.pixlab.io/txtremove"
input_path = Path("./campaign-image.png")

with input_path.open("rb") as image_file:
    response = requests.post(
        endpoint,
        files={
            "file": (input_path.name, image_file, "image/png"),
        },
        data={
            "key": os.environ["PIXLAB_API_KEY"],
        },
        timeout=60,
    )

reply = response.json()

if reply.get("status") != 200:
    raise RuntimeError(reply.get("error", "Image text removal failed"))

extension = reply.get("extension", "png")
output_path = Path(f"campaign-image-cleaned.{extension}")
output_path.write_bytes(base64.b64decode(reply["imgData"]))

print(f"Saved cleaned image to {output_path}")

Run the script:

python remove_image_text.py

The request uploads the source image in the multipart file field. On success, the default response includes imgData, mimeType, and extension, allowing your application to decode the image and save it with the correct file extension. See the TXT-REMOVE HTTP parameters and response fields for all supported options.

Step 4

Upload an Image with Server-Side JavaScript

Node.js 18 and newer provide fetch, FormData, and Blob. Create remove-image-text.mjs:

import { readFile, writeFile } from "node:fs/promises";

const endpoint = "https://api.pixlab.io/txtremove";
const apiKey = process.env.PIXLAB_API_KEY;

if (!apiKey) {
  throw new Error("PIXLAB_API_KEY is not set");
}

const input = await readFile("./campaign-image.png");
const form = new FormData();

form.append("file", new Blob([input], { type: "image/png" }), "campaign-image.png");
form.append("key", apiKey);

const response = await fetch(endpoint, {
  method: "POST",
  body: form,
});

const reply = await response.json();

if (reply.status !== 200) {
  throw new Error(reply.error || "Image text removal failed");
}

const extension = reply.extension || "png";
const output = Buffer.from(reply.imgData, "base64");
const outputPath = `campaign-image-cleaned.${extension}`;

await writeFile(outputPath, output);
console.log(`Saved cleaned image to ${outputPath}`);

Run it:

node remove-image-text.mjs
Keep this request on your server, worker, or serverless backend. Calling the endpoint directly from public browser code would reveal your API key to visitors.

Step 5

Return Raw Image Bytes Instead of JSON

If the next stage of your pipeline expects an image stream rather than Base64 JSON, set blob=true in the multipart form data. TXT-REMOVE then returns raw image bytes on success.

import os
from mimetypes import guess_extension
from pathlib import Path

import requests

input_path = Path("./campaign-image.png")

with input_path.open("rb") as image_file:
    response = requests.post(
        "https://api.pixlab.io/txtremove",
        files={"file": (input_path.name, image_file, "image/png")},
        data={
            "key": os.environ["PIXLAB_API_KEY"],
            "blob": "true",
        },
        timeout=60,
    )

content_type = response.headers.get("content-type", "")

if "application/json" in content_type:
    error_reply = response.json()
    raise RuntimeError(error_reply.get("error", "Image text removal failed"))

response.raise_for_status()
media_type = content_type.partition(";")[0].strip()
extension = guess_extension(media_type) or ".bin"
Path(f"campaign-image-cleaned{extension}").write_bytes(response.content)

Raw-byte mode avoids Base64 decoding and is useful when output goes directly to object storage, an image editor, or another media-processing service. Read the returned Content-Type to determine the exact image format instead of assuming PNG.

Step 6

Store Output in Your Own AWS S3 Bucket

For workflows that need persistent output URLs, connect an AWS S3 bucket through the PixLab Console. When S3 output is configured, the JSON response can contain a link to the cleaned image in your bucket instead of Base64 imgData.

Handle both documented response shapes:

if reply.get("link"):
    print("Output stored in your bucket:", reply["link"])
elif reply.get("imgData"):
    output_bytes = base64.b64decode(reply["imgData"])
else:
    raise RuntimeError("The response did not include image output")

Your organization controls the destination bucket, its access permissions, lifecycle rules, and retention settings.

Step 7

Process Images in Bulk with Bounded Concurrency

TXT-REMOVE processes one image per request. For catalog migrations, localized campaign updates, licensed archives, or recurring high-volume cleanup jobs, use a queue or bounded worker pool instead of sending an uncontrolled burst of requests.

This Python example processes up to four images at a time. Adjust the worker count to match your account limits and infrastructure. It uses the default Base64 JSON response; if your account writes output to S3, adapt the worker to consume the returned link.

import base64
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import requests

endpoint = "https://api.pixlab.io/txtremove"
api_key = os.environ["PIXLAB_API_KEY"]
input_directory = Path("./authorized-input")
output_directory = Path("./cleaned-output")
output_directory.mkdir(exist_ok=True)


def remove_image_text(image_path):
    with image_path.open("rb") as image_file:
        response = requests.post(
            endpoint,
            files={"file": (image_path.name, image_file)},
            data={"key": api_key},
            timeout=60,
        )

    reply = response.json()
    if reply.get("status") != 200:
        raise RuntimeError(reply.get("error", "Image text removal failed"))

    extension = reply.get("extension", "png")
    output_path = output_directory / f"{image_path.stem}.{extension}"
    output_path.write_bytes(base64.b64decode(reply["imgData"]))
    return output_path


images = [
    path
    for path in input_directory.iterdir()
    if path.suffix.lower() in {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
]

with ThreadPoolExecutor(max_workers=4) as executor:
    jobs = {executor.submit(remove_image_text, image): image for image in images}

    for job in as_completed(jobs):
        source = jobs[job]
        try:
            print(f"Processed {source.name} -> {job.result()}")
        except Exception as error:
            print(f"Failed {source.name}: {error}")

For production workloads, place jobs in a durable queue, apply timeouts, retry only temporary failures, and send unsuccessful or visually difficult items to a review queue. Record request status and operational identifiers without logging source images or Base64 output.

Understanding the TXT-REMOVE Response

The default JSON response contains these fields:

TXT-REMOVE JSON response fields
FieldMeaning
status200 indicates success. Other values indicate an error.
imgDataBase64-encoded cleaned image when S3 output is not configured.
mimeTypeOutput MIME type, such as image/png.
extensionOutput file extension, such as png or jpeg.
linkOutput URL in your connected AWS S3 bucket, returned instead of imgData.
errorError description when status is not 200.

When blob=true, the response contains raw image bytes instead of this JSON structure. After your application validates the result, the cleaned output is ready to be consumed by another service, used in an app, or displayed on a website, marketplace, or online store without another text-removal step.

TXT-REMOVE or BG-REMOVE: Which Endpoint Should You Use?

The two endpoints solve different image-editing tasks:

Comparison of TXT-REMOVE and BG-REMOVE endpoints
TaskEndpoint
Erase captions, labels, timestamps, annotations, or permitted watermarks while preserving the surrounding image.TXT-REMOVE Text and Watermark Removal API
Isolate the main subject and remove the complete image background.BG-REMOVE Background Removal API

Use TXT-REMOVE when the background should remain and only text-like overlays need reconstruction. Use BG-REMOVE when the output should be a subject cutout. A workflow can call both endpoints when both operations are required, but evaluate each stage separately because every transformation changes the input for the next one.

Privacy and Image Retention

PixLab processes images submitted to TXT-REMOVE in volatile memory and automatically purges them when processing finishes. PixLab does not persist the API payload unless storage or export is explicitly enabled.

If you connect your own AWS S3 bucket, output can be written directly to that bucket. Your organization controls its permissions and retention policy. Review the PixLab Privacy Policy for current processing and retention details.

Avoid placing source images, credentials, or Base64 output in routine application logs, analytics events, or error-reporting systems.

Common Text and Watermark Removal Workflows

The same integration pattern can support several authorized business workflows:

Ecommerce catalogs

Clear obsolete price labels, campaign badges, captions, or temporary promotional text from product images your business controls.

Marketing and localization

Remove approved copy before adding translated or updated messaging to campaign assets.

Screenshots and interface assets

Clean labels, annotations, timestamps, and test content from images owned by your organization.

Publishing and media archives

Process licensed image collections containing outdated captions or temporary overlays.

Creative applications

Add automatic image text removal to an editor, content-management system, or internal asset tool.

Moderation pipelines

Clean approved user-generated images after confirming ownership, consent, and policy requirements.

Troubleshooting

The API returns an error instead of an image

Read the JSON error field. Confirm that the API key is valid, the request uses POST, the content type is multipart/form-data, the image is in the file field, and the account is within its current limits.

Some text remains in the image

Very small, stylized, transparent, distorted, or low-contrast text may be more difficult to detect. Test representative inputs and route exceptions to review rather than repeatedly processing the same output.

The reconstructed area needs review

Large overlays and text crossing faces, fine details, gradients, or dense repeating patterns can make reconstruction more difficult. Automated removal estimates what was hidden; it does not recover unavailable original pixels.

The response does not contain imgData

Check for a link field. When an AWS S3 bucket is connected, the API can return an output URL in your bucket instead of Base64 image data.

Raw-byte mode returns JSON

Error responses can still use JSON. Inspect the response Content-Type before saving raw bytes and read the error field when JSON is returned.

A bulk job overwhelms the application

Reduce the worker count, add queue backpressure, and respect your account limits. Bounded concurrency makes failures easier to retry and prevents a large folder from creating an uncontrolled request burst.

FAQ

Text and Watermark Removal API Questions

How do I remove text from an image with the PixLab API?

Upload a local image in the file field of a multipart POST request to the TXT-REMOVE endpoint. The API detects text-like regions automatically, reconstructs the affected areas, and returns the cleaned image as Base64 data, raw image bytes, or a link in your connected AWS S3 bucket.

Does TXT-REMOVE require a mask or text coordinates?

No. TXT-REMOVE detects text-like regions automatically. The request does not require a mask, bounding boxes, coordinates, or a separate OCR response.

Can I use the API to remove watermarks?

You may use TXT-REMOVE on images you own or are authorized to modify. You must not remove copyright notices, branding, stock-photo watermarks, or other ownership marks from third-party content without permission.

Can TXT-REMOVE process images in bulk?

Yes. TXT-REMOVE processes one image per request. For bulk text removal, distribute requests through a bounded queue, worker pool, serverless workflow, or scheduled job while staying within your account limits.

What output does the text-removal API return?

By default, TXT-REMOVE returns JSON containing Base64-encoded image data, the MIME type, and the file extension. Set blob=true to receive raw image bytes, or connect your own AWS S3 bucket to receive a link to the output stored in your bucket.

Does PixLab retain images submitted to TXT-REMOVE?

PixLab processes submitted API images in volatile memory and automatically purges them when processing finishes. PixLab does not persist the payload unless storage or export is explicitly enabled, such as output written to your connected AWS S3 bucket.

Build with TXT-REMOVE

Start Removing Text from Authorized Images

Use the 7-day free trial to test TXT-REMOVE with the captions, labels, timestamps, and authorized overlays your application handles. Review the results and current account limits before moving the workflow into production.