Background Removal API (Base64)#

Removes the background from a base64-encoded image and returns a ready-to-use base64-encoded PNG with a transparent background. One call, no client-side compositing.

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, a large upload, and a large RGBA PNG download.
  • The response is heavy: a 4-channel RGBA PNG (lossless), inflated a further ~33% by base64. For web display you rarely need a full-resolution transparent PNG.
  • Resizing the input before sending is the main optimization, but note it also caps your output resolution (see below).
If you need a full-resolution master, this is the slow path. The Alpha Matte endpoint lets you keep the full-res original locally, send a 1024px proxy, and apply the matte to the original after. That is faster and preserves full resolution. This cutout endpoint trades that control for convenience.

When to use this endpoint#

This endpoint is the right choice when you want a finished, ready-to-use transparent PNG with zero compositing on your side:

  • One-shot integrations: Drop in a single call, get a PNG back, done.
  • Web and display-sized images: Avatars, thumbnails, product shots sized for the page, not full-resolution masters.
  • Browser and mobile apps: Embed the result in JSON and render it client-side via a data:image/png;base64, URI.
  • Serverless functions: Process and return images without file system access.

Consider the alpha matte instead when#

  • You need a full-resolution master (keep the original locally, apply a 1024 proxy matte). See the recommended workflow.
  • You render multiple outputs from one image (different backgrounds, shadows, glows, blurs) and want to call the API only once.
  • You composite onto saturated or dark backgrounds and need straight-alpha control to avoid edge fringing.
  • Latency or bandwidth matters: a 1-channel grayscale matte is roughly 1/3 to 1/4 the size of this RGBA cutout.

Base64 vs Binary: Choose base64 for browser environments, JSON APIs, and structured data workflows. Use the Binary variant for server-to-server transfers, file I/O, and backend processing pipelines.

Endpoint#

POST /v1.0/image-without-background-base64

Base URL: https://api.withoutbg.com

Authentication#

Include your API key in the request header:

Authentication Header

X-API-Key: YOUR_API_KEY
Security: Never embed API keys in client-side code. Use environment variables or a secrets manager, and proxy requests through your backend.

Request#

Content-Type: application/json

Body#

Request Body

{
  "image_base64": "<base64_encoded_image_data>"
}

Fields#

  • image_base64 (string, required) — The input image encoded as Base64. Supported input formats: JPEG, PNG, WebP, TIFF, BMP, GIF. Maximum file size: 10 MB (before encoding).
Tip: When sending Base64, do not include the data URI prefix (e.g., data:image/png;base64,). Send only the raw Base64 string.

Response#

Content-Type: application/json

Body#

Response Body

{
  "img_without_background_base64": "<base64_encoded_transparent_image>"
}

Fields#

  • img_without_background_base64 (string) — The result image encoded as Base64 PNG (RGBA) with a transparent background. To display it directly in a browser, prepend data:image/png;base64,.
Examples

Examples#

Browser (upload and display)#

The point of base64 in the browser is the round-trip: encode a user-selected file, POST it, then render the result inline. Strip the data URI prefix before sending, and add data:image/png;base64, back to display the result.

HTML

<input type="file" id="file" accept="image/*" />
<img id="result" alt="Result with background removed" />

JavaScript

Proxy through your backend in production so the API key is never exposed

1document.getElementById("file").addEventListener("change", async (e) => {
2  const file = e.target.files[0];
3  if (!file) return;
4
5  // Encode file to raw base64 (strip the "data:...;base64," prefix)
6  const dataUrl = await new Promise((resolve) => {
7    const reader = new FileReader();
8    reader.onload = () => resolve(reader.result);
9    reader.readAsDataURL(file);
10  });
11  const imageBase64 = dataUrl.split(",")[1];
12
13  const res = await fetch("/api/remove-background", {
14    method: "POST",
15    headers: { "Content-Type": "application/json" },
16    body: JSON.stringify({ image_base64: imageBase64 }),
17  });
18  const { img_without_background_base64 } = await res.json();
19
20  // Add the prefix back to render it
21  document.getElementById("result").src =
22    `data:image/png;base64,${img_without_background_base64}`;
23});

cURL#

cURL Example

Send a base64-encoded image and receive the result

curl -X POST "https://api.withoutbg.com/v1.0/image-without-background-base64" \
  -H "X-API-Key: $WITHOUTBG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image_base64": "<base64_encoded_image_data>"}'

Node.js (fetch)#

Node.js Example

Process images using Node.js native fetch

1import fs from "node:fs";
2
3const apiKey = process.env.WITHOUTBG_API_KEY;
4const imageBase64 = fs.readFileSync("input.jpg").toString("base64");
5
6const res = await fetch("https://api.withoutbg.com/v1.0/image-without-background-base64", {
7  method: "POST",
8  headers: {
9    "Content-Type": "application/json",
10    "X-API-Key": apiKey
11  },
12  body: JSON.stringify({ image_base64: imageBase64 })
13});
14
15if (!res.ok) {
16  const error = await res.text();
17  throw new Error(`HTTP ${res.status}: ${error}`);
18}
19
20const data = await res.json();
21const outputPng = Buffer.from(data.img_without_background_base64, "base64");
22fs.writeFileSync("output.png", outputPng);

Python (requests)#

Python Example

Process images using Python requests library

1import base64
2import os
3import requests
4
5API_KEY = os.environ["WITHOUTBG_API_KEY"]
6
7with open("input.jpg", "rb") as f:
8    b64 = base64.b64encode(f.read()).decode("utf-8")
9
10resp = requests.post(
11    "https://api.withoutbg.com/v1.0/image-without-background-base64",
12    headers={"Content-Type": "application/json", "X-API-Key": API_KEY},
13    json={"image_base64": b64},
14    timeout=60,
15)
16resp.raise_for_status()
17
18out_b64 = resp.json()["img_without_background_base64"]
19with open("output.png", "wb") as out:
20    out.write(base64.b64decode(out_b64))

cURL (from an image file to Base64 on the fly)#

cURL with File Encoding

macOS/Linux example using base64 CLI

1# macOS/Linux example using base64 CLI
2BASE64_DATA=$(base64 -w 0 input.jpg) # use `-w 0` (GNU) or omit on macOS
3curl -X POST "https://api.withoutbg.com/v1.0/image-without-background-base64" \
4  -H "X-API-Key: $WITHOUTBG_API_KEY" \
5  -H "Content-Type: application/json" \
6  -d "{\"image_base64\": \"$BASE64_DATA\"}"

Python SDK#

Python developers can use the official withoutbg Python SDK instead of making raw HTTP requests:

Python SDK Example

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

Status Codes & Limits

Status Codes#

Success (200 OK)#

Returns JSON with the transparent PNG as Base64.

Error Responses#

All errors return JSON:

Error Response Format

{
  "detail": "Error message here"
}
HTTP status codes and their meanings for the Base64 background removal API
CodeStatusDescription
200successReturns JSON with the transparent PNG as Base64
400errorValidation Error - Invalid JSON or missing image_base64 field
401errorInvalid API Key - Missing or invalid API key
402warningInsufficient credit. Please top up API credits.
403errorCredits Expired. Please top up API credits. If you have existing credits, they will be reactivated.
413errorFile size too large. Maximum file size is 10.0 MB
415errorUnsupported Media Type. Supported formats are: JPEG, PNG, WebP, TIFF, BMP, GIF.
422errorValidation Error - Invalid Base64 string or corrupt image
429warningRate limit (7 request/minute) exceeded
5xxerrorInternal Server Error. Please contact support: contact@withoutbg.com

Rate limit: 7 requests per minute per API key

Max input size: 10 MB (before base64 encoding)

Best Practices

Best Practices#

  • Resize to your display size before sending: You rarely need a full-resolution transparent PNG for web or app display. Resizing the input reduces upload size, response size, and latency. If you need a full-resolution master, use the Alpha Matte workflow instead, which keeps the original local.
  • Trim Base64 prefixes: Send only the raw Base64 payload, not data URI schemes. Add data:image/png;base64, back only when displaying the result.
  • Re-encode for delivery: The response is a lossless RGBA PNG. For shipping to clients, consider converting to WebP to cut file size while keeping transparency.
  • Retry on 429: Implement exponential backoff when rate limited
  • Monitor credits: Check /available-credit to track usage and set up alerts
  • Timeouts: Set HTTP timeouts of at least 60 seconds for large images
  • Error handling: Parse JSON error responses and handle 402/403 by prompting users to top up credits
  • Security: Store API keys in environment variables or secrets managers, never in code repositories
  • Caching: Cache processed images on your side to save credits and reduce latency
Troubleshooting

Troubleshooting#

  • 400/422 errors: Ensure Content-Type: application/json and image_base64 is a valid Base64 string of a supported image format
  • 401 errors: Verify your API key is correct and included in the X-API-Key header
  • 402/403 credit errors: Check /available-credit and top up if needed
  • 413 errors: Input image exceeds 10 MB after decoding. Compress or resize before encoding
  • 415 errors: Ensure the decoded image is in a supported format (JPEG, PNG, WebP, TIFF, BMP, GIF)
  • 429 rate limit: Implement exponential backoff. Wait progressively longer between retries
  • Transparent output looks solid: If your viewer shows a black/white background, the PNG is still transparent. Verify with an editor that supports alpha, or display it on a checkered background
  • 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 endpoint and composite yourself
  • Soft edges at high resolution: Expected. Edge detail is capped at 1024px inference, regardless of input resolution
Related Endpoints
Quick Checklist

Quick Checklist#

  • Confirmed you want a ready-made cutout, not a full-res master via alpha matte
  • Input resized to display size (full-res cutouts are large and edges are 1024-capped)
  • POST to /v1.0/image-without-background-base64
  • X-API-Key header present with valid key
  • Content-Type: application/json header set
  • JSON body with image_base64 field (raw Base64, no data URI prefix)
  • Base64 string decoded size under 10 MB
  • HTTP timeout set to at least 60 seconds
  • Handle 402/403 credit errors by checking /available-credit
  • Implement exponential backoff for 429 rate limit errors
  • Never expose API keys in client-side code
  • Decode img_without_background_base64 (prepend data:image/png;base64, to display)