Automatic background removal is useful when product photos, marketplace listings, campaign assets, portraits, or user uploads need a transparent subject cutout. Instead of maintaining a segmentation pipeline, your application can send each image to the PixLab BG-REMOVE API and receive processed image data through one REST endpoint.
To test the examples with your own images, start the PixLab 7-day free trial and create an API key. Current account limits and plan details are shown in the Console, so you can evaluate representative inputs before choosing a paid plan.
Overview
What You Will Build
By the end of this tutorial, you will be able to:
- Send an image to
/bgremovewithout creating a mask. - Upload a local file with
POSTor use a public URL withGET. - Decode the default Base64 response and save the output image.
- Request raw image bytes with
blob=true. - Call the API from server-side JavaScript without exposing your key.
- Process larger image collections with bounded concurrency.
Before You Start
- 1A PixLab API key from the 7-day free trial in the PixLab Console.
- 2Python 3 with the
requestspackage, or Node.js 18 or newer. - 3One or more images you own or are authorized to process.
- 4The BG-REMOVE API reference for complete parameter and response documentation.
How the Background Removal Request Works
BG-REMOVE uses one endpoint:
https://api.pixlab.io/bgremove
| Input | Method | Recommended use |
|---|---|---|
| Public image URL | GET | The source image is reachable through a public HTTPS URL. |
| Local image file | POST with multipart/form-data | The image is local, private, or supplied by an application upload flow. |
Foreground detection is automatic. You do not need to send a mask, bounding box, coordinate list, or manually traced subject outline.
| Parameter | Purpose |
|---|---|
key | Your PixLab API key. |
img | Public source image URL for a GET request. |
blob | Set to true to receive raw image bytes instead of JSON. |
compress | Set to false to disable default JPEG compression. PNG output remains lossless. |
By default, the API returns JSON containing Base64-encoded image data. If you connect your own AWS S3 bucket, it can instead return a link to the result written to that bucket.
Step 1
Start the Trial and Create an API Key
Open the PixLab Console, start the 7-day free trial, and create your API key. Keep the key on your backend and load it from an environment variable.
PowerShell
$env:PIXLAB_API_KEY="YOUR_API_KEY"
Bash or Zsh
export PIXLAB_API_KEY="YOUR_API_KEY"
The examples below read PIXLAB_API_KEY from the environment, keeping the credential separate from your source code.
Step 2
Choose a Suitable Input Image
Background removal quality depends partly on the source image. Before sending production assets:
- Prefer a clear subject with enough contrast from the background.
- Avoid severe motion blur and heavy compression.
- Keep important subject edges inside the frame.
- Review images containing glass, fine hair, fur, shadows, or semi-transparent details.
- Test representative product categories instead of relying on a single ideal image.


BG-REMOVE is designed to preserve detailed boundaries, but no automatic segmentation system is perfect for every image. Review commercially important output before publishing it to a website, marketplace, or online store.
Step 3
Upload a Local Image with Python
Install the Python dependency:
python -m pip install requests
Create remove_background.py:
import base64
import os
from pathlib import Path
import requests
endpoint = "https://api.pixlab.io/bgremove"
input_path = Path("./product-photo.jpg")
with input_path.open("rb") as image_file:
response = requests.post(
endpoint,
files={
"file": (input_path.name, image_file, "image/jpeg"),
},
data={
"key": os.environ["PIXLAB_API_KEY"],
},
timeout=60,
)
reply = response.json()
if reply.get("status") != 200:
raise RuntimeError(reply.get("error", "Background removal failed"))
extension = reply.get("extension", "png")
output_path = Path(f"product-photo-no-background.{extension}")
output_path.write_bytes(base64.b64decode(reply["imgData"]))
print(f"Saved background-removed image to {output_path}")
Run the script:
python remove_background.py
The request sends the source image in the multipart file field. The response includes imgData, mimeType, and extension, allowing the application to decode and save the correct output format. See the BG-REMOVE HTTP parameters and response fields for all supported options.
Step 4
Remove a Background from a Public Image URL
Use GET when the source image is already available through a public URL:
import base64
import os
from pathlib import Path
import requests
response = requests.get(
"https://api.pixlab.io/bgremove",
params={
"img": "https://example.com/product-photo.jpg",
"key": os.environ["PIXLAB_API_KEY"],
},
timeout=60,
)
reply = response.json()
if reply.get("status") != 200:
raise RuntimeError(reply.get("error", "Background removal failed"))
extension = reply.get("extension", "png")
Path(f"output.{extension}").write_bytes(base64.b64decode(reply["imgData"]))
The URL must be reachable by the API. Use a direct upload instead when the image is private or available only inside your network.
Step 5
Upload an Image with Server-Side JavaScript
Node.js 18 and newer provide fetch, FormData, and Blob. Create remove-background.mjs:
import { readFile, writeFile } from "node:fs/promises";
const endpoint = "https://api.pixlab.io/bgremove";
const apiKey = process.env.PIXLAB_API_KEY;
if (!apiKey) {
throw new Error("PIXLAB_API_KEY is not set");
}
const input = await readFile("./product-photo.jpg");
const form = new FormData();
form.append("file", new Blob([input], { type: "image/jpeg" }), "product-photo.jpg");
form.append("key", apiKey);
const response = await fetch(endpoint, {
method: "POST",
body: form,
});
const reply = await response.json();
if (reply.status !== 200) {
throw new Error(reply.error || "Background removal failed");
}
const extension = reply.extension || "png";
const output = Buffer.from(reply.imgData, "base64");
const outputPath = `product-photo-no-background.${extension}`;
await writeFile(outputPath, output);
console.log(`Saved background-removed image to ${outputPath}`);
Run it:
node remove-background.mjs
Step 6
Return Raw Image Bytes Instead of JSON
For an image pipeline that does not need Base64 JSON, set blob=true. The response then contains raw image bytes:
import os
from mimetypes import guess_extension
from pathlib import Path
import requests
response = requests.get(
"https://api.pixlab.io/bgremove",
params={
"img": "https://example.com/product-photo.jpg",
"key": os.environ["PIXLAB_API_KEY"],
"blob": "true",
},
timeout=60,
)
content_type = response.headers.get("content-type", "")
if "application/json" in content_type:
error_reply = response.json()
raise RuntimeError(error_reply.get("error", "Background removal failed"))
response.raise_for_status()
media_type = content_type.partition(";")[0].strip()
extension = guess_extension(media_type) or ".bin"
Path(f"product-photo-no-background{extension}").write_bytes(response.content)
Raw-byte output avoids Base64 decoding and can be forwarded directly to storage or another media-processing step. Use the returned Content-Type to determine the exact format instead of assuming PNG.
Step 7
Use Your Own AWS S3 Bucket for Output
If your workflow needs persistent output URLs, connect an AWS S3 bucket through the PixLab Console. When S3 output is configured, the JSON response can contain a link to the file in your bucket instead of Base64 imgData.
Your application should handle both documented response shapes:
if reply.get("link"):
print("Output stored in your bucket:", reply["link"])
elif reply.get("imgData"):
output_bytes = base64.b64decode(reply["imgData"])
else:
raise RuntimeError("The response did not include image output")
Use bucket permissions, lifecycle rules, and retention settings that match your application requirements.
Step 8
Process Image Collections with Bounded Concurrency
BG-REMOVE handles one source image per request. For product catalogs, marketplace assets, or recurring high-volume jobs, distribute requests through a queue or worker pool instead of sending an uncontrolled burst.
This Python example uses four workers. Adjust the value to match your account limits and infrastructure:
import base64
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
endpoint = "https://api.pixlab.io/bgremove"
api_key = os.environ["PIXLAB_API_KEY"]
input_directory = Path("./catalog-input")
output_directory = Path("./catalog-output")
output_directory.mkdir(exist_ok=True)
def remove_background(image_path):
with image_path.open("rb") as image_file:
response = requests.post(
endpoint,
files={"file": (image_path.name, image_file)},
data={"key": api_key},
timeout=60,
)
reply = response.json()
if reply.get("status") != 200:
raise RuntimeError(reply.get("error", "Background removal failed"))
extension = reply.get("extension", "png")
output_path = output_directory / f"{image_path.stem}.{extension}"
output_path.write_bytes(base64.b64decode(reply["imgData"]))
return output_path
images = [
path
for path in input_directory.iterdir()
if path.suffix.lower() in {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
]
with ThreadPoolExecutor(max_workers=4) as executor:
jobs = {executor.submit(remove_background, image): image for image in images}
for job in as_completed(jobs):
source = jobs[job]
try:
print(f"Processed {source.name} -> {job.result()}")
except Exception as error:
print(f"Failed {source.name}: {error}")
For a production workload, place jobs in a durable queue, record completion status without logging image contents, retry only temporary failures, and send unsuccessful items to a review or dead-letter queue.
Understanding the BG-REMOVE Response
The default JSON response contains these fields:
| Field | Meaning |
|---|---|
status | 200 indicates success. Other values indicate an error. |
imgData | Base64-encoded output image when S3 output is not configured. |
mimeType | Output MIME type, such as image/png. |
extension | Output file extension, such as png or jpeg. |
link | Output URL in your connected AWS S3 bucket, returned instead of imgData. |
error | Error description when status is not 200. |
When blob=true, the response contains raw image bytes instead of this JSON structure. After your application validates the result, the output is ready to be used in an app or shown on a website, marketplace, or online store without additional background processing.
Privacy and Image Retention
PixLab processes submitted BG-REMOVE images in volatile memory and automatically purges them when processing finishes. PixLab does not persist the API payload unless storage or export is explicitly enabled.
When you connect your own AWS S3 bucket, output can be written directly to that bucket. Your organization controls its permissions and retention policy. Review the PixLab Privacy Policy for current processing and retention details.
Avoid placing source images or Base64 output in ordinary application logs, analytics events, or error-reporting systems.
Common Background Removal Workflows
Ecommerce catalogs
Prepare product cutouts for storefronts, catalog feeds, and marketplace listings.
Marketing production
Place approved campaign subjects onto new layouts and backgrounds.
Creative applications
Add automatic background removal to an editor or asset-management tool.
Profile images
Isolate people for profile-photo services and branded templates.
Back-office processing
Clean incoming image batches through scheduled workers or internal tools.
For a browser interface that processes batches without code, see the PixLab Bulk Background Remover. For application integration, continue with the BG-REMOVE API reference.
Troubleshooting
The API returns an error instead of an image
Read the JSON error field. Confirm the API key, public image URL, multipart field name, source file, and account limits before retrying.
The public image URL does not work
Confirm that the URL points directly to an image and is reachable without authentication. Use a multipart POST upload for private images.
Fine edges need review
Hair, fur, glass, semi-transparent materials, low contrast, compression, and motion blur can make segmentation more difficult. Test representative production images and route important exceptions to review.
The response does not contain imgData
Check for a link field. When an AWS S3 bucket is connected, the API can return the output URL in your bucket instead of Base64 image data.
Raw-byte mode returns JSON
An error response can still be JSON. Check the response Content-Type before saving raw bytes and read the error field when JSON is returned.
FAQ
Background Removal API Questions
How do I remove an image background with the PixLab API?
Send a public image URL with GET or upload a local image with a multipart POST request to the BG-REMOVE endpoint. The API detects the foreground automatically and returns the processed image as Base64 data, raw image bytes, or a link in your connected AWS S3 bucket.
Does the background removal API require a mask?
No. BG-REMOVE detects the foreground automatically, so the request does not require a segmentation mask, subject coordinates, or a manually traced outline.
Can I upload an image directly to the BG-REMOVE API?
Yes. Send a multipart/form-data POST request with the local image in the file field and your API key in the form data. You can also use GET when the source image is available through a public URL.
Can I process images in bulk with BG-REMOVE?
Yes. BG-REMOVE processes one image per request. For bulk background removal, distribute requests through a bounded queue, worker pool, serverless workflow, or scheduled job while staying within your account limits.
What output does the background removal API return?
By default, BG-REMOVE returns JSON containing Base64-encoded image data, the MIME type, and the file extension. Set blob=true to receive raw image bytes, or connect your own AWS S3 bucket to receive a link to the output stored in your bucket.
Does PixLab retain images submitted to BG-REMOVE?
PixLab processes submitted API images in volatile memory and automatically purges them when processing finishes. PixLab does not persist the payload unless storage or export is explicitly enabled, such as output written to your connected AWS S3 bucket.
Build with BG-REMOVE
Start Removing Image Backgrounds
Use the 7-day free trial to test BG-REMOVE with the image types your application actually handles. Review the results and current account limits before moving the workflow into production.