📖 Tutorial

Background Removal API —
Perfect Product Photos in Seconds

⏱ 10 min read 🔧 curl · Python · Node.js 💡 Beginner friendly 📅 Updated March 2026

1. What is Background Removal API

PixelAPI's Background Removal API automatically removes backgrounds from product images, returning a transparent PNG or white-background JPEG — ready for e-commerce listings on Meesho, Flipkart, Amazon, and Myntra.

Uses state-of-the-art AI segmentation to precisely detect product edges, even for complex products like jewelry, transparent glass, or garments with fine details.

Use Cases

  • 🛍 Meesho/Flipkart compliance — White background product images required for listings
  • 📦 Catalog automation — Process thousands of supplier photos automatically
  • 🎨 Creative compositing — Place products on custom backgrounds
  • 👗 Virtual try-on prep — Create clean garment images for try-on API
  • 🏪 Website product grids — Consistent look across all product cards

2. Getting Started

  1. Sign up at pixelapi.dev/app
  2. Get your API key from the dashboard
  3. Set export PIXELAPI_KEY="pk_your_key_here"
💡

The background removal API is synchronous — you get the result directly in the response, unlike the async virtual try-on API.

3. Your First API Call

API Endpoint

POST https://api.pixelapi.dev/v1/remove-bg
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json

Request Parameters

ParameterTypeRequiredDescription
image_urlstring✓URL of the image to process
output_formatstring✗png (transparent) or jpg (white bg). Default: png
sizestring✗preview (625px), full (original size). Default: full
curl -X POST https://api.pixelapi.dev/v1/remove-bg \
  -H "Authorization: Bearer $PIXELAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image_url": "https://example.com/product.jpg"}' \
  | python3 -c "
import sys, json, base64
data = json.load(sys.stdin)
img = base64.b64decode(data['result_b64'])
open('output.png', 'wb').write(img)
print('Saved output.png')
"
import requests
import base64
import os

api_key = os.environ.get("PIXELAPI_KEY")

def remove_background(image_url: str, output_format: str = "png") -> bytes:
    """Remove background from an image URL. Returns image bytes."""
    response = requests.post(
        "https://api.pixelapi.dev/v1/remove-bg",
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        },
        json={
            "image_url": image_url,
            "output_format": output_format
        }
    )
    response.raise_for_status()
    data = response.json()
    
    # Decode base64 result
    img_b64 = data["result_b64"]
    if "," in img_b64:
        img_b64 = img_b64.split(",")[1]
    return base64.b64decode(img_b64)

# Usage
img_bytes = remove_background("https://example.com/product.jpg", "png")
with open("product_nobg.png", "wb") as f:
    f.write(img_bytes)
print(f"Saved! Size: {len(img_bytes):,} bytes")
import 'dotenv/config';
import { writeFileSync } from 'fs';

const BASE_URL = 'https://api.pixelapi.dev';
const apiKey = process.env.PIXELAPI_KEY;

async function removeBackground(imageUrl, outputFormat = 'png') {
  const response = await fetch(`${BASE_URL}/v1/remove-bg`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ image_url: imageUrl, output_format: outputFormat })
  });

  if (!response.ok) {
    const err = await response.json();
    throw new Error(`API Error: ${err.detail || response.status}`);
  }

  const data = await response.json();
  let b64 = data.result_b64;
  if (b64.includes(',')) b64 = b64.split(',')[1];
  return Buffer.from(b64, 'base64');
}

// Usage
const imgBuffer = await removeBackground('https://example.com/product.jpg', 'png');
writeFileSync('product_nobg.png', imgBuffer);
console.log(`✅ Saved! ${imgBuffer.length.toLocaleString()} bytes`);

4. Image Tips

AspectRecommendedNotes
FormatJPEG, PNG, WebPAny common format works
Resolution512px+ on shortest sideHigher = better edge detection
LightingEven, studio lightingHarsh shadows may affect edges
BackgroundAny single color works bestComplex BGs still work well
Product typeClothing, accessories, productsWorks for most product categories
✅

Works great:

  • Clothing & garments
  • Electronics & gadgets
  • Shoes & footwear
  • Food & beverages
  • Furniture & home decor
⚠️

May need review:

  • Transparent/glass objects
  • Very fine hair/fur detail
  • Products same color as BG
  • Heavily patterned backgrounds

5. Handling the Result

The API returns the processed image as a base64-encoded string. Here's how to handle different output formats:

# Get transparent PNG (for overlaying on custom backgrounds)
img_bytes = remove_background(
    "https://example.com/product.jpg",
    output_format="png" # Transparent background
)
with open("product_transparent.png", "wb") as f:
    f.write(img_bytes)

# Can now overlay on any background using Pillow
from PIL import Image
import io

product = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
background = Image.new("RGBA", product.size, (240, 240, 240, 255)) # Light gray
composite = Image.alpha_composite(background, product)
composite.convert("RGB").save("product_on_gray.jpg", "JPEG", quality=95)
# Get white background JPEG (Meesho/Flipkart compliant)
img_bytes = remove_background(
    "https://example.com/product.jpg",
    output_format="jpg" # White background
)
with open("product_whitebg.jpg", "wb") as f:
    f.write(img_bytes)
print("✅ Meesho-compliant product image saved!")
// Display transparent PNG in browser
async function processAndDisplay(imageUrl) {
  const data = await fetch('/api/remove-bg', {
    method: 'POST',
    body: JSON.stringify({ image_url: imageUrl })
  }).then(r => r.json());
  
  const b64 = data.result_b64;
  const src = b64.includes(',') ? b64 : `data:image/png;base64,${b64}`;
  
  const img = document.getElementById('result-img');
  img.src = src;
  img.style.display = 'block';
}

// React component
function BgRemovedImage({ src }) {
  const [result, setResult] = React.useState(null);
  
  async function process() {
    const data = await removeBackgroundAPI(src);
    setResult(`data:image/png;base64,${data.result_b64}`);
  }
  
  return (
    <div>
      <button onClick={process}>Remove Background</button>
      {result && <img src={result} alt="No background" />}
    </div>
  );
}

6. Batch Processing

Process hundreds of product images efficiently:

import asyncio
import aiohttp
import base64
import os
from pathlib import Path

api_key = os.environ.get("PIXELAPI_KEY")

async def remove_bg_async(session, image_url: str, output_path: str):
    """Remove background from a single image asynchronously."""
    async with session.post(
        "https://api.pixelapi.dev/v1/remove-bg",
        headers={"Authorization": f"Bearer {api_key}"},
        json={"image_url": image_url, "output_format": "png"}
    ) as resp:
        data = await resp.json()
        img_b64 = data["result_b64"]
        if "," in img_b64:
            img_b64 = img_b64.split(",")[1]
        
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, "wb") as f:
            f.write(base64.b64decode(img_b64))
        print(f"✅ {output_path}")

async def process_batch(products: list[dict]):
    """Process a batch of products concurrently (max 5 at a time)."""
    semaphore = asyncio.Semaphore(5) # Respect rate limits
    
    async def process_one(product):
        async with semaphore:
            await remove_bg_async(
                session, product["url"], product["output"]
            )
    
    async with aiohttp.ClientSession() as session:
        tasks = [process_one(p) for p in products]
        await asyncio.gather(*tasks)

# Example: process 50 product images
products = [
    {"url": f"https://cdn.example.com/product_{i}.jpg", 
     "output": f"output/product_{i}_nobg.png"}
    for i in range(1, 51)
]

asyncio.run(process_batch(products))
print(f"✅ Processed {len(products)} images!")

7. E-commerce Use Cases

Meesho Catalog Compliance

Meesho requires white background product images. Here's a complete automation script:

import requests, base64, os
from PIL import Image
import io

def meesho_compliant_image(image_url: str, output_path: str):
    """
    Convert any product photo to Meesho-compliant format:
    - White background
    - Square crop (1:1 ratio)
    - Minimum 500x500px
    """
    # Step 1: Remove background (get transparent PNG)
    response = requests.post(
        "https://api.pixelapi.dev/v1/remove-bg",
        headers={"Authorization": f"Bearer {os.environ['PIXELAPI_KEY']}"},
        json={"image_url": image_url, "output_format": "png"}
    )
    data = response.json()
    img_b64 = data["result_b64"]
    if "," in img_b64: img_b64 = img_b64.split(",")[1]
    
    # Step 2: Composite on white, make square
    product = Image.open(io.BytesIO(base64.b64decode(img_b64))).convert("RGBA")
    size = max(product.size[0], product.size[1], 500)
    canvas = Image.new("RGBA", (size, size), (255, 255, 255, 255))
    
    # Center the product
    x = (size - product.size[0]) // 2
    y = (size - product.size[1]) // 2
    canvas.paste(product, (x, y), product)
    
    # Save as JPEG
    canvas.convert("RGB").save(output_path, "JPEG", quality=95)
    print(f"✅ Meesho-ready: {output_path}")

meesho_compliant_image(
    "https://example.com/supplier_product.jpg",
    "meesho_ready.jpg"
)

8. Pricing & Limits

₹0.6 per image

= 10 credits per background removal

Free Trial Available

No credit card required

RATE LIMIT
60 req/min
MAX FILE SIZE
10 MB
RESPONSE TIME
1–3 seconds
OUTPUT FORMATS
PNG, JPEG

9. FAQ

What's the difference between PNG and JPG output?▼

PNG (transparent) — Returns a PNG with alpha channel. Use when you want to overlay on custom backgrounds or need transparency.

JPG (white background) — Returns a JPEG with white background. Use for Meesho/Flipkart compliance, faster to download, smaller file size.

Can I process images from local disk?▼

Currently only URLs are supported. Upload your image to S3, Cloudinary, or any CDN and use the public URL. Direct file upload support is coming soon.

How do I handle transparent objects like glass?▼

Semi-transparent objects (glass, bottles, etc.) are challenging for any BG removal AI. Results are generally good but may have slight imperfections around transparent areas. For best results:

  • Photograph glass objects against a contrasting background
  • Use even lighting to minimize reflections
  • Review results and manually touch up if needed
How many images can I process per day?▼

There's no daily cap — you're limited only by your credit balance and the rate limit (60 requests/minute). With 5,000 credits you can process 500 images. Enterprise plans include dedicated limits and bulk credit discounts.

Start Processing Product Images 🚀

Free credits to get started. No credit card required.
Process your first product image in under 1 minute.

Start Free Trial →    View Full API Docs