Alpha Matte (Base64)#
Extract the transparency mask (alpha matte) from an image and receive it as a base64-encoded PNG in JSON format. Perfect for browser apps, JSON pipelines, and embedded workflows.
Why Use Alpha Matte Over a Transparent PNG#
- Non-destructive compositing: keep original RGB separate from transparency to avoid halos caused by premultiplied alpha. Control spill suppression and matte expansion yourself.
- Higher quality edges: preserve soft hair, motion blur, and defocus as continuous alpha. Tune thresholds, feathering, and refine with erosion or dilation per target platform.
- One mask, many outputs: reuse the same matte to render multiple backgrounds, sizes, and styles (shadows, outlines, glows) without reprocessing the subject each time.
- Pipeline flexibility: apply as CSS
mask-image, Canvas or WebGL mask, native platform masks, or per-frame in video without relying on PNG decoder behavior. - Linear-light control: composite in linear color and choose straight or premult pipelines explicitly. Transparent PNGs can bake assumptions that vary by renderer.
- Performance and storage: masks compress well and are tiny to cache and ship. Generate variants at the edge or client from a single cached matte.
- Post-processing control: selectively blur, recolor, relight, or inpaint background or subject using the matte as a selection, not just as final transparency.
- ML and CV integration: use as soft labels for segmentation or matting training and quality metrics, beyond simple cutout rendering.
When to Use This Endpoint#
Use the base64 alpha matte endpoint when:
- Browser-based applications: Embed masks directly in JSON responses for JavaScript processing
- JSON API workflows: Need structured data format rather than raw binary
- Client-side compositing: Apply masks using Canvas, WebGL, or CSS
mask-image - Serverless functions: Process and return masks without file system access
- Multi-output rendering: Generate multiple composites (shadows, glows, backgrounds) from one mask
Base64 vs Binary: Choose base64 for browser environments and JSON-based workflows. Use the Binary variant for server-to-server transfers and direct file I/O.
Matte vs Cutout: Use this endpoint when you need the transparency mask for compositing. If you want the final cut-out image with transparent background, use Background Removal instead.
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_KEYRequest#
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 input formats: JPEG, PNG, WebP, TIFF, BMP, GIF. Maximum file size: 10 MB (before encoding).
data:image/png;base64,). Send only the raw Base64 string.Response#
Content-Type: application/json
Body#
Response Body
{
"alpha_base64": "<base64_encoded_alpha_channel_image>"
}Fields#
alpha_base64(string) - The alpha matte encoded as Base64 grayscale PNG. White pixels (255) represent fully opaque areas, black (0) represents transparent, and gray values represent partial transparency.
Error Responses#
All errors return JSON:
Error Response Format
{
"detail": "Error message here"
}Rate limit: 7 requests per minute per API key
Examples#
cURL#
cURL Example
Send a base64-encoded image and receive the alpha matte
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>"}'Node.js (fetch)#
Node.js Example
Process images using Node.js and fetch
1import fs from "node:fs";
2
3const apiKey = process.env.WITHOUTBG_API_KEY;
4const imageBase64 = fs.readFileSync("input.png").toString("base64");
5
6const res = await fetch("https://api.withoutbg.com/v1.0/alpha-channel-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 alphaPng = Buffer.from(data.alpha_base64, "base64");
22fs.writeFileSync("alpha-mask.png", alphaPng);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.png", "rb") as f:
8 img_b64 = base64.b64encode(f.read()).decode("utf-8")
9
10r = requests.post(
11 "https://api.withoutbg.com/v1.0/alpha-channel-base64",
12 headers={"Content-Type": "application/json", "X-API-Key": API_KEY},
13 json={"image_base64": img_b64},
14 timeout=60,
15)
16r.raise_for_status()
17
18alpha_b64 = r.json()["alpha_base64"]
19with open("alpha-mask.png", "wb") as f:
20 f.write(base64.b64decode(alpha_b64))cURL (from image file to Base64 on the fly)#
cURL with Base64 Encoding
macOS/Linux example using base64 CLI
1# macOS/Linux example using base64 CLI
2BASE64_DATA=$(base64 -w 0 input.jpg 2>/dev/null || base64 -i input.jpg)
3curl -X POST "https://api.withoutbg.com/v1.0/alpha-channel-base64" \
4 -H "X-API-Key: $WITHOUTBG_API_KEY" \
5 -H "Content-Type: application/json" \
6 -d "{\"image_base64\": \"$BASE64_DATA\"}"Status Codes#
| Code | Status | Meaning |
|---|---|---|
400 | error | Validation Error - Invalid JSON or missing image_base64 field |
401 | error | Invalid API Key - Missing or invalid API key |
402 | warning | Insufficient credit. Please top up API credits. |
403 | error | Credits Expired. Please top up API credits. If you have existing credits, they will be reactivated. |
413 | error | File size too large. Maximum file size is 10.0 MB |
415 | error | Unsupported Media Type. Supported formats are: JPEG, PNG, WebP, TIFF, BMP, GIF. |
422 | error | Validation Error - Invalid Base64 string or corrupt image |
429 | warning | Rate limit (7 request/minute) exceeded |
5xx | error | Internal 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)
Best Practices#
- Trim Base64 prefixes: Send only the raw Base64 payload, not data URI schemes
- Pre-resize: Downscale large images before encoding to reduce payload size and latency
- Retry on 429: Implement exponential backoff when rate limited
- Monitor credits: Check
/available-creditto 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 the alpha matte and reuse it for multiple composites to save credits
Troubleshooting#
- 400/422 errors: Ensure
Content-Type: application/jsonandimage_base64is a valid Base64 string of a supported image format - 401 errors: Verify your API key is correct and included in the
X-API-Keyheader - 402/403 credit errors: Check
/available-creditand 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
- Mask appears solid: Some viewers don't render grayscale PNGs correctly. Verify with an image editor
- Halos or artifacts: This is the raw matte. Apply spill suppression or edge refinement on your side for production composites
Related Endpoints#
- Alpha Matte (Binary):
POST /v1.0/alpha-channel- Returns the alpha matte as binary PNG for server workflows - Background Removal (Base64):
POST /v1.0/image-without-background-base64- Returns the cut-out image (RGB + alpha) instead of just the mask - Background Removal (Binary):
POST /v1.0/image-without-background- Binary variant of background removal - Credits:
GET /available-credit- Check remaining API credits
Quick Checklist#
POSTto/v1.0/alpha-channel-base64X-API-Keyheader present with valid keyContent-Type: application/jsonheader set- JSON body with
image_base64field (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
alpha_base64from response to get PNG mask