Background Removal (Binary)#
Process an image and receive the cut-out PNG (with transparency) directly in the response body. This endpoint is built for servers, CLIs, and batch pipelines that want a binary image back rather than JSON/base64.
How the model works#
The model runs inference at a maximum of 1024 pixels on the longer side. If you send a larger image, the API downscales it to 1024 for inference, then applies the resulting matte back to your full-resolution RGB.
- The returned PNG keeps your input RGB resolution, but the alpha edges carry only 1024px of detail. Sending a 4000px image gives you a 4000px cutout with 1024-quality edges and a large upload/download.
- Why binary:
multipart/form-datasends the raw file bytes, avoiding the ~33% size inflation of base64 on the upload, and the response streams back as raw PNG bytes with no JSON parse or decode step. For server-to-server and batch volume, this is the efficient choice.
When to Use This Endpoint#
Use the binary background removal endpoint when:
- Server-to-server workflows: Direct file I/O without JSON or base64 overhead
- CLI tools and scripts: Save the transparent PNG directly to disk
- Batch processing: Process many images with the smallest per-request payload (see the throttled batch example)
- File-based pipelines: Integration with systems that expect standard image files
- Simple cutouts: You need the final transparent PNG, not separate RGB and alpha for compositing
Consider the alpha matte instead when#
- You need a full-resolution master (keep the original locally, apply a 1024 proxy matte)
- You render multiple outputs from one image (different backgrounds, shadows, glows) and want to call the API only once
- You composite onto saturated or dark backgrounds and need straight-alpha control to avoid edge fringing
- Throughput matters: a 1-channel grayscale matte is the smallest, fastest transfer of all four endpoints
Binary vs Base64: Choose binary for server environments, file-based workflows, and direct image output. Use the Base64 variant for browser apps, JSON APIs, or when you need to embed images in structured data.
Endpoint#
POST /v1.0/image-without-background
Base URL: https://api.withoutbg.com
Authentication#
Provide your API key in the request header:
Authentication Header
X-API-Key: <your_api_key>Request#
Headers#
X-API-Key: <your_api_key>(required)- The request must be
multipart/form-data.
Form fields#
file(required): The image file to process.
Supported formats: JPEG, PNG, WebP, TIFF, BMP, GIF
Max file size: 10 MB
file field as the raw file part (not base64). If you need base64/JSON output, use the Base64 variant of the API.Response#
- 200 OK — Binary image in the body
Content-Type: image/png- Transparent background (alpha channel)
The response body is the processed PNG. Save it to disk (e.g., no-bg.png).
Usage Examples#
cURL#
cURL Example
Upload an image file and save the transparent PNG result
curl -X POST \
-H "X-API-Key: $WITHOUTBG_API_KEY" \
-F "file=@/path/to/input.jpg" \
--output no-bg.png \
https://api.withoutbg.com/v1.0/image-without-backgroundNode.js (stream to disk)#
Node.js Example
Stream the response body straight to a file instead of buffering in memory
1import fs from "node:fs";
2import { Readable } from "node:stream";
3import { pipeline } from "node:stream/promises";
4import FormData from "form-data";
5
6const form = new FormData();
7form.append("file", fs.createReadStream("input.jpg"));
8
9const res = await fetch("https://api.withoutbg.com/v1.0/image-without-background", {
10 method: "POST",
11 headers: {
12 "X-API-Key": process.env.WITHOUTBG_API_KEY,
13 ...form.getHeaders(),
14 },
15 body: form,
16});
17
18if (!res.ok) {
19 throw new Error(`HTTP ${res.status}: ${await res.text()}`);
20}
21
22await pipeline(Readable.fromWeb(res.body), fs.createWriteStream("no-bg.png"));Python (requests, stream to disk)#
Python Example
Stream the response to disk with the requests library
1import os
2import requests
3
4with open("input.jpg", "rb") as f:
5 r = requests.post(
6 "https://api.withoutbg.com/v1.0/image-without-background",
7 headers={"X-API-Key": os.environ["WITHOUTBG_API_KEY"]},
8 files={"file": f},
9 timeout=60,
10 stream=True,
11 )
12
13r.raise_for_status()
14with open("no-bg.png", "wb") as out:
15 for chunk in r.iter_content(chunk_size=8192):
16 out.write(chunk)Browser (via your backend)#
A binary endpoint is handy in the browser for downloading a finished file, but never call the API directly from the browser (it exposes your key). Call your own backend, which proxies to withoutBG, and download the returned blob.
Browser Example
Proxy through your backend, then download the blob
1const formData = new FormData();
2formData.append("file", fileInput.files[0]);
3
4// Your backend attaches the X-API-Key and forwards to withoutBG
5const res = await fetch("/api/remove-background", { method: "POST", body: formData });
6if (!res.ok) throw new Error(`HTTP ${res.status}`);
7
8const blob = await res.blob();
9const url = URL.createObjectURL(blob);
10const a = document.createElement("a");
11a.href = url;
12a.download = "no-bg.png";
13a.click();
14URL.revokeObjectURL(url);Batch processing (throttled for 7 req/min)#
The rate limit is 7 requests per minute. Throttle your batch and back off on 429 so a large job doesn't fail partway through.
Throttled Batch (Python)
Space requests ~8.6s apart and retry 429s with exponential backoff
1import os
2import time
3import requests
4
5API = "https://api.withoutbg.com/v1.0/image-without-background"
6HEADERS = {"X-API-Key": os.environ["WITHOUTBG_API_KEY"]}
7MIN_INTERVAL = 60 / 7 # ~8.6s between requests to stay under 7/min
8
9def remove_background(path: str, out_path: str, max_retries: int = 5) -> None:
10 for attempt in range(max_retries):
11 with open(path, "rb") as f:
12 r = requests.post(API, headers=HEADERS, files={"file": f}, timeout=60)
13 if r.status_code == 200:
14 with open(out_path, "wb") as out:
15 out.write(r.content)
16 return
17 if r.status_code == 429:
18 wait = min(2 ** attempt, 30) # exponential backoff, capped
19 time.sleep(wait)
20 continue
21 r.raise_for_status()
22 raise RuntimeError(f"Failed after {max_retries} retries: {path}")
23
24inputs = ["a.jpg", "b.jpg", "c.jpg"]
25for path in inputs:
26 remove_background(path, path.replace(".jpg", "-no-bg.png"))
27 time.sleep(MIN_INTERVAL)cURL with error handling (bash)#
On error the body is JSON, not a PNG. Inspect the saved file instead of firing a second request.
cURL with Error Handling
Production-ready cURL script with proper error handling
1set -euo pipefail
2API=https://api.withoutbg.com/v1.0/image-without-background
3
4http_code=$(curl -sS -w "%{http_code}" -o no-bg.png \
5 -H "X-API-Key: $WITHOUTBG_API_KEY" \
6 -F "file=@input.jpg" "$API")
7
8if [ "$http_code" != "200" ]; then
9 echo "Request failed with status: $http_code" >&2
10 cat no-bg.png >&2 # error body is JSON
11 rm -f no-bg.png
12 exit 1
13fiPython SDK#
Python developers can use the official withoutbg Python SDK instead of making raw HTTP requests:
Python SDK Usage
Use the official Python SDK for cleaner API integration
1from withoutbg import remove_background
2
3# Cloud API (uses this endpoint)
4img = remove_background("input.jpg", api_key="sk_your_api_key")
5img.save("output.png")The SDK handles authentication, retries, error handling, and provides a cleaner API. It also supports local processing (free) with the Focus v1.0.0 model.
Learn more: Python SDK Documentation
Errors#
All error responses follow this format:
Error Response Format
{
"detail": "Error message here"
}| Status | Description | When it happens |
|---|---|---|
401 | Invalid API Key | Missing or invalid API key |
402 | Insufficient credit. Please top up API credits. | Account has no credits. Check balance with /available-credit |
403 | Credits Expired. Please top up API credits. If you have existing credits, they will be reactivated. | Credits have expired. Top up to reactivate |
413 | File size too large. Maximum file size is 10.0 MB | File exceeds 10 MB limit |
415 | Unsupported Media Type. Supported formats are: JPEG, PNG, WebP, TIFF, BMP, GIF. | Wrong file format |
422 | Validation Error | Missing required fields or corrupt image |
429 | Rate limit (7 request/minute) exceeded | Too many requests. Implement exponential backoff |
5xx | Internal Server Error. Please contact support: contact@withoutbg.com | Temporary server issue. Retry with backoff |
Best Practices#
- Resize before upload: You rarely need a full-resolution cutout. Downscaling reduces upload size, response size, and latency. For full-resolution masters, use the Alpha Matte (Binary) workflow, which keeps the original local.
- Throttle batches: Stay within 7 requests/minute. Space requests ~8.6s apart and back off on 429 (see the batch example)
- Stream large responses: Pipe the response body to disk rather than buffering it entirely in memory
- Timeouts: Set HTTP timeouts of at least 60 seconds to cover upload and processing time
- Retries: Implement exponential backoff for transient 429 and 5xx errors
- Monitor credits: Poll /available-credit to track usage and set up alerts
- Security: Store API keys in environment variables or secrets managers, never in code repositories
- Error handling: Parse JSON error responses and handle 402/403 by prompting users to top up credits
- Idempotence: Hash input files for deduplication if you need to handle retries
Troubleshooting#
- 401 errors: Verify your API key is correct and included in the
X-API-Keyheader - 402/403 credit errors: Check /available-credit and top up if needed
- 413 errors: Input image exceeds 10 MB. Compress or resize before uploading
- 415 errors: Ensure the file is one of the supported formats (JPEG, PNG, WebP, TIFF, BMP, GIF)
- 422 errors: Verify the
filefield is present and contains a valid image - 429 rate limit: Throttle to 7 requests/minute and implement exponential backoff
- Transparent output looks solid: If your viewer shows a black/white background, the PNG is still transparent. Verify with an editor that supports alpha
- Edge fringing on colored backgrounds: The cutout uses baked alpha. When compositing onto saturated or dark backgrounds you may see a faint halo. For straight-alpha control, use the Alpha Matte (Binary) endpoint and composite yourself
- Soft edges at high resolution: Expected. Edge detail is capped at 1024px inference, regardless of input resolution
Quick Checklist#
- Confirmed you want a ready-made cutout, not a full-res master via alpha matte
- Input resized appropriately (full-res cutouts are large and edges are 1024-capped)
POSTto/v1.0/image-without-backgroundX-API-Keyheader present with valid keymultipart/form-datawithfilefield (notimage)- File is under 10 MB and in supported format
- HTTP timeout set to at least 60 seconds
- Save response body as
*.png - Throttle batches to 7 requests/minute with exponential backoff on 429
- Handle 402/403 credit errors by checking /available-credit
- Never expose API keys in client-side code
Related Endpoints#
- Alpha Matte (Binary):
POST /v1.0/alpha-channel— Returns just the alpha mask. Smallest, fastest transfer; best for full-res masters and multi-output pipelines - Background Removal (Base64):
POST /v1.0/image-without-background-base64— Returns Base64 JSON for browser/embedded workflows - Alpha Matte (Base64):
POST /v1.0/alpha-channel-base64— Base64 variant of alpha matte with compositing benefits explained - Credits:
GET /available-credit— Check remaining API credits