March 6, 2026 · Tutorial

Automate Background Removal Like a Pro with PixelAPI

Remove backgrounds from images in seconds — no Photoshop skills required

The Problem: Background Removal Without the Hassle

Ever needed to remove a background from an image for e-commerce, social media, or design projects — but didn't want to manually edit each one in Photoshop or Figma?

That's where PixelAPI comes in — a fast, affordable API that lets you remove backgrounds (or generate custom ones) in seconds.

1. Setup: Get PixelAPI Working

Option A: Python (Recommended for Automation)

pip install requests

Save your API key from PixelAPI's dashboard as an environment variable:

export PIXELAPI_KEY="your_api_key_here"  # Linux/Mac

Option B: curl (Quick CLI Testing)

This example used a discontinued tool and has been removed. Use the supported endpoint examples on this page or browse the current tool catalogue.

2. Basic Background Removal

Python Example

import requests
import os

API_KEY = os.getenv("PIXELAPI_KEY")
IMAGE_URL = "https://example.com/your-image.jpg"

response = requests.post(
    "https://api.pixelapi.dev/v1/image/remove-bg",
    headers={"X-API-KEY": API_KEY},
    json={"image_url": IMAGE_URL}
)

if response.status_code == 200:
    with open("output.png", "wb") as f:
        f.write(response.content)
    print("✅ Background removed! Saved as 'output.png'")
else:
    print(f"❌ Error: {response.text}")

curl Example

curl -X POST https://api.pixelapi.dev/v1/image/remove-bg \
  -H "X-API-KEY: your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"image_url": "https://example.com/your-image.jpg"}' \
  --output output.png
Key Notes: Input can be a URL or base64-encoded image. Output is a PNG with transparency. Free tier allows 100 requests/day.

Standalone background image generation — Discontinued

Standalone background image generation has been discontinued. Use the current background replacement documentation for photo editing.

4. Batch Processing (Multiple Images)

image_urls = [
    "https://example.com/product1.jpg",
    "https://example.com/product2.jpg",
]

for i, url in enumerate(image_urls, 1):
    response = requests.post(
        "https://api.pixelapi.dev/v1/image/remove-bg",
        headers={"X-API-KEY": API_KEY},
        json={"image_url": url}
    )

    if response.status_code == 200:
        with open(f"output_{i}.png", "wb") as f:
            f.write(response.content)
        print(f"✅ Processed {url}")
    else:
        print(f"❌ Failed {url}: {response.text}")
Optimization Tip: Add time.sleep(0.5) between requests to avoid rate limits. For speed, use ThreadPoolExecutor for parallel processing.

5. Error Handling & Best Practices

ErrorCauseSolution
401 UnauthorizedWrong API keyCheck PIXELAPI_KEY
403 ForbiddenRate limit exceededWait 1 hour (free tier)
429 Too Many RequestsToo many callsUpgrade plan or add delays
400 Bad RequestInvalid URL/base64Use a valid image source
try:
    response = requests.post(
        "https://api.pixelapi.dev/v1/image/remove-bg",
        headers={"X-API-KEY": API_KEY},
        json={"image_url": "invalid-url"},
        timeout=10
    )
    response.raise_for_status()
    print("Success!")
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error: {err}")
except requests.exceptions.RequestException as err:
    print(f"Request Failed: {err}")

6. Complete Automation Script

import requests
import os
import time
from dotenv import load_dotenv

load_dotenv()
API_KEY = os.getenv("PIXELAPI_KEY")
INPUT_DIR = "input_images/"
OUTPUT_DIR = "output_images/"

def process_image(image_url, output_filename, prompt=None):
    """Remove BG or generate custom background."""
    endpoint = "remove-bg" if not prompt else "generate"
    payload = {"image_url": image_url}
    if prompt:
        payload.update({"model": "AI image generation", "prompt": prompt})

    try:
        response = requests.post(
            f"https://api.pixelapi.dev/v1/image/{endpoint}",
            headers={"X-API-KEY": API_KEY},
            json=payload,
            timeout=15
        )
        response.raise_for_status()

        with open(f"{OUTPUT_DIR}{output_filename}", "wb") as f:
            f.write(response.content)
        print(f"✅ {output_filename} processed!")
        return True
    except Exception as e:
        print(f"❌ Failed {output_filename}: {e}")
        return False

if __name__ == "__main__":
    for filename in os.listdir(INPUT_DIR):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            image_url = f"file://{os.path.join(INPUT_DIR, filename)}"
            process_image(image_url, filename.replace(".jpg", "_bg_removed.png"))
            process_image(
                image_url,
                filename.replace(".jpg", "_white_bg.png"),
                prompt="clean white background, no shadows"
            )
            time.sleep(0.5)

7. Benchmarks & Cost Comparison

ServiceFree TierCost (1000 images)SpeedQuality
PixelAPI 100/day ~$5 Fast (~3s) AI image generation (best)
Remove.bg1000/mo~$10Medium (~5s)Good
Open-source (U²-Net)Free$0 (but slow)Slow (~30s)Medium

Next Steps

Start Automating Today

5,000 free credits (24-hour trial) on signup. No credit card required. Process your first image in under 60 seconds.

Get Your Free API Key →