Alpha Matte (Base64)#

Extract a grayscale transparency mask from an image and receive it as a base64-encoded PNG in a JSON response.

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 before inference, interpolates the matte back to your input dimensions, and returns it at your original resolution.

Sending a 4000 × 3000 image returns a 4000 × 3000 matte, but edge precision is capped at 1024px inference quality. You get no quality gain over pre-resizing client-side.

Pre-resizing to 1024px on the longer side before sending is the correct approach for any larger image:

  • Upload size drops from several MB to ~150–300 KB (resized JPEG). Upload is the dominant latency cost in any request.
  • Response size is proportionally smaller.
  • Resampling control: you choose the downsample filter (Lanczos gives the best edge alignment for matting) rather than relying on server defaults.
  • You apply the matte to the untouched original, not to a copy that has passed through the server.

Why alpha matte over background removal#

The background removal endpoint returns a 4-channel RGBA PNG: it composites for you. The alpha matte endpoint returns a 1-channel grayscale PNG, typically 1/3 to 1/4 the response size, and hands control back to you.

  • Keep the full-resolution original locally. Send a resized JPEG proxy to the API, get the matte, upscale it, apply it to the untouched original. You never round-trip your master image through a lossy transfer at full resolution.
  • One mask, many outputs. Generate shadows, background blurs, glows, and composites from a single cached matte without re-calling the API.
  • Composite with straight alpha. Apply alpha yourself to avoid dark halos caused by premultiplied compositing. Composite in linear light if accuracy matters.
  • Pipeline flexibility. Use the mask as CSS mask-image, a Canvas or WebGL texture, a per-frame video mask, or a selection for inpainting, relighting, or background blur.
  • ML and CV pipelines. Use as soft labels for segmentation training, quality metrics, or matte refinement downstream.

For any image larger than 1024px on the longer side, this is the fastest and most efficient approach:

  1. Keep the original locally.
  2. Resize a copy so the longer side = 1024 px (Lanczos filter). Encode as JPEG at quality ≥ 90.
  3. POST the resized copy to /v1.0/alpha-channel-base64. Receive alpha_base64.
  4. Decode the matte. Upscale it to the original dimensions (bilinear or bicubic).
  5. Apply as straight alpha to the original RGB.
  6. Optionally: erode/dilate edges, suppress color spill, or feather for your target platform.
Edge quality note: When you upscale the matte back to the original resolution, edges carry only the precision captured at 1024px. For most subjects (people, products, animals) this is excellent. For very fine hair against a busy background at 4K, the limiting factor is the matte precision, not your RGB.

Python (Pillow)#

Recommended workflow — Python

Resize proxy, get matte, upscale, apply to original

1from PIL import Image
2import base64, io, os, requests
3
4API_KEY = os.environ["WITHOUTBG_API_KEY"]
5
6# 1. Keep original
7orig = Image.open("input.jpg").convert("RGB")
8orig_w, orig_h = orig.size
9
10# 2. Resize proxy to max 1024px, encode JPEG q=90
11scale = min(1.0, 1024 / max(orig_w, orig_h))
12proxy = orig.resize((round(orig_w * scale), round(orig_h * scale)), Image.LANCZOS)
13buf = io.BytesIO()
14proxy.save(buf, format="JPEG", quality=90)
15img_b64 = base64.b64encode(buf.getvalue()).decode()
16
17# 3. Call the API
18r = requests.post(
19    "https://api.withoutbg.com/v1.0/alpha-channel-base64",
20    headers={"Content-Type": "application/json", "X-API-Key": API_KEY},
21    json={"image_base64": img_b64},
22    timeout=60,
23)
24r.raise_for_status()
25
26# 4. Decode matte and upscale to original dimensions
27matte_bytes = base64.b64decode(r.json()["alpha_base64"])
28matte = Image.open(io.BytesIO(matte_bytes)).convert("L")
29matte = matte.resize((orig_w, orig_h), Image.BICUBIC)
30
31# 5. Apply straight alpha to original
32orig.putalpha(matte)
33orig.save("output.png")

Node.js (sharp)#

Recommended workflow — Node.js

npm install sharp

1import sharp from "sharp";
2import fs from "node:fs";
3
4const API_KEY = process.env.WITHOUTBG_API_KEY;
5const MAX_SIDE = 1024;
6
7// 1. Load original
8const origBuffer = fs.readFileSync("input.jpg");
9const { width: origW, height: origH } = await sharp(origBuffer).metadata();
10
11// 2. Resize proxy to max 1024px, encode JPEG q=90
12const scale = Math.min(1, MAX_SIDE / Math.max(origW, origH));
13const proxyBuffer = await sharp(origBuffer)
14  .resize(Math.round(origW * scale), Math.round(origH * scale), { kernel: "lanczos3" })
15  .jpeg({ quality: 90 })
16  .toBuffer();
17
18// 3. Call the API
19const res = await fetch("https://api.withoutbg.com/v1.0/alpha-channel-base64", {
20  method: "POST",
21  headers: { "Content-Type": "application/json", "X-API-Key": API_KEY },
22  body: JSON.stringify({ image_base64: proxyBuffer.toString("base64") }),
23});
24if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
25const { alpha_base64 } = await res.json();
26
27// 4. Decode matte, upscale to original dimensions (raw pixel buffer)
28const matteBuffer = Buffer.from(alpha_base64, "base64");
29const matteRaw = await sharp(matteBuffer)
30  .resize(origW, origH, { kernel: "mitchell" })
31  .raw()
32  .toBuffer();
33
34// 5. Apply straight alpha to original
35await sharp(origBuffer)
36  .joinChannel(matteRaw, { raw: { width: origW, height: origH, channels: 1 } })
37  .png()
38  .toFile("output.png");

When to use base64 vs binary#

Choose this endpoint (base64) for browser environments and JSON-based pipelines. Use the binary variant for server-to-server transfers where you write the matte directly to disk or stream it downstream.

Endpoint#

POST /v1.0/alpha-channel-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

Headers#

  • X-API-Key: YOUR_API_KEY (required)
  • Content-Type: application/json (required)

Body#

Request Body

{
  "image_base64": "<base64_encoded_image_data>"
}

Fields#

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

Response#

Content-Type: application/json

Body#

Response Body

{
  "alpha_base64": "<base64_encoded_alpha_channel_image>"
}

Fields#

  • alpha_base64 (string) — The alpha matte as a Base64-encoded grayscale PNG. White (255) = fully opaque, black (0) = fully transparent, gray values = partial transparency.

Error Responses#

All errors return JSON:

Error Response Format

{
  "detail": "Error message here"
}
Reference Examples

Reference examples#

cURL (quick test)#

cURL

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

cURL (encode file on the fly)#

cURL with Base64 Encoding

macOS/Linux

BASE64_DATA=$(base64 -w 0 input.jpg 2>/dev/null || base64 -i input.jpg)
curl -X POST "https://api.withoutbg.com/v1.0/alpha-channel-base64" \
  -H "X-API-Key: $WITHOUTBG_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"image_base64\": \"$BASE64_DATA\"}"
Status Codes & Limits

Status Codes#

HTTP status codes and their meanings for the Alpha Matte (Base64) API
CodeStatusMeaning
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 & Size Limits#

  • Rate limit: 7 requests/minute per API key
  • Max input size: 10 MB (pre-encoding). Pre-resizing to 1024px makes this limit irrelevant in practice.
Best Practices

Best Practices#

  • Pre-resize to 1024px. Resize so the longer side is 1024px before encoding. This is the single most impactful optimization: it reduces upload size, response size, and total latency with no quality trade-off.
  • Use JPEG for the proxy at quality ≥ 90. Low-quality JPEG introduces blocking artifacts at edges where matting is hardest. Stay at 90+.
  • Apply straight alpha, not premultiplied. Multiply alpha by the linear RGB values yourself to avoid dark halos at semi-transparent edges.
  • Cache and reuse the matte. Generate multiple composites (shadows, blurs, background swaps) from the same cached mask without re-calling the API.
  • Strip Base64 prefixes. Send only the raw Base64 string, not data URI schemes (data:image/png;base64,).
  • Retry on 429. Implement exponential backoff. The rate limit is 7 requests/minute per API key.
  • Monitor credits. Check /available-credit and handle 402/403 by prompting users to top up.
  • Set HTTP timeouts. At least 60 seconds for large images.
Troubleshooting

Troubleshooting#

  • 400/422 errors: Ensure Content-Type: application/json and image_base64 is a valid Base64 string of a supported format.
  • 401 errors: Verify your API key is correct and 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. Resize or compress before encoding.
  • 415 errors: Ensure the decoded image is JPEG, PNG, WebP, TIFF, BMP, or GIF.
  • 429 rate limit: Implement exponential backoff.
  • Mask appears solid white or black: Some viewers don't render grayscale PNGs correctly. Verify in an image editor.
  • Halos or dark edges after compositing: You are applying premultiplied alpha. Use straight alpha instead.
  • Soft edges at high resolution: Expected. Edge precision is capped at 1024px inference detail. Apply optional matte refinement (erosion, feathering) if needed.
Related Endpoints
Quick Checklist

Quick Checklist#

  • Image pre-resized to max 1024px on the longer side
  • Encoded as JPEG quality ≥ 90 (or PNG if hard edges are critical)
  • POST to /v1.0/alpha-channel-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)
  • Decoded input size under 10 MB
  • HTTP timeout ≥ 60 s
  • Handle 402/403 credit errors
  • Exponential backoff for 429 errors
  • API keys stored in environment variables, not source code
  • Matte upscaled to original dimensions before applying
  • Straight alpha applied to original RGB, not premultiplied