ScreenshotNeo

BlogHow-to

How to Remove an Image Background with an API

Learn the background-removal API workflow with runnable cURL, Python and Node.js examples, provider limits, errors, cost and production guidance.

By the ScreenshotNeo team1 October 20268 min read

A background-removal API accepts an image, segments the foreground subject, and returns a processed image with the background removed. The production workflow is: authenticate, upload the image (or provide an image URL when supported), choose an output format, validate the response, and store or return the result.

Photoroom documents POST https://sdk.photoroom.com/v1/segment with an x-api-key header and a multipart image_file field. remove.bg documents uploads and image-URL inputs, authenticated with an API key or OAuth access token. Read Photoroom’s quickstart and the remove.bg API reference before integrating.

Quick start with Photoroom

The following command sends a local image and writes the returned image to cutout.png. Replace the placeholder key and file path.

curl --request POST \
  --url https://sdk.photoroom.com/v1/segment \
  --header "x-api-key: YOUR_PHOTOROOM_API_KEY" \
  --form image_file=@input.jpg \
  --output cutout.png

PNG is the default output described by Photoroom. Its Remove Background API accepts PNG, JPEG, WEBP and HEIC inputs and can return PNG, JPEG or WEBP. Confirm current format behavior in the provider documentation before relying on it in a pipeline. Photoroom API details

Python: remove a background from a local file

from pathlib import Path
import os
import requests

api_key = os.environ["PHOTOROOM_API_KEY"]
source = Path("input.jpg")
destination = Path("cutout.png")

with source.open("rb") as image:
    response = requests.post(
        "https://sdk.photoroom.com/v1/segment",
        headers={"x-api-key": api_key},
        files={"image_file": (source.name, image, "image/jpeg")},
        timeout=120,
    )

response.raise_for_status()
destination.write_bytes(response.content)
print(f"Wrote {destination} ({destination.stat().st_size} bytes)")

Install the dependency with python -m pip install requests, then set PHOTOROOM_API_KEY in the process environment. Do not put the key in browser JavaScript or commit it to source control.

Node.js: multipart upload

Node.js 18 or newer includes fetch, FormData and Blob. This example reads a file, sends it as image_file, and saves the binary response.

import { readFile, writeFile } from "node:fs/promises";

const apiKey = process.env.PHOTOROOM_API_KEY;
if (!apiKey) throw new Error("Set PHOTOROOM_API_KEY first");

const input = "input.jpg";
const output = "cutout.png";
const bytes = await readFile(input);
const form = new FormData();
form.append("image_file", new Blob([bytes], { type: "image/jpeg" }), input);

const response = await fetch("https://sdk.photoroom.com/v1/segment", {
  method: "POST",
  headers: { "x-api-key": apiKey },
  body: form,
  signal: AbortSignal.timeout(120000),
});

if (!response.ok) {
  const detail = await response.text();
  throw new Error(`Background removal failed (${response.status}): ${detail}`);
}

await writeFile(output, Buffer.from(await response.arrayBuffer()));
console.log(`Wrote ${output}`);

Using remove.bg

remove.bg supports an uploaded file or an image URL and authenticates with an API key or OAuth access token. The exact endpoint parameters and output options are provider-defined, so keep the request aligned with its current API reference.

Upload a file with cURL

curl -H "X-Api-Key: YOUR_REMOVE_BG_API_KEY" \
  -F "image_file=@input.jpg" \
  -o cutout.png \
  https://api.remove.bg/v1.0/removebg

Submit an image URL

curl -H "X-Api-Key: YOUR_REMOVE_BG_API_KEY" \
  -F "image_url=https://example.com/product.jpg" \
  -o cutout.png \
  https://api.remove.bg/v1.0/removebg

Its API documentation lists a 22 MB input-file limit and a maximum input resolution of 50 megapixels. Output options and resolution vary by requested format. remove.bg advertises 50 free low-resolution API calls per month on its product page; verify current limits and credit rules before budgeting.

Choose an API by checking the whole pipeline

Question Why it matters What to verify
Input formats Your uploader may produce formats the service does not accept. PNG, JPEG, WEBP, HEIC and any camera-specific variants.
Output format Transparent backgrounds normally require an alpha-capable format. Whether PNG or another selected format preserves transparency.
File and pixel limits Large originals can fail before segmentation starts. Maximum bytes, megapixels, dimensions and request body size.
Authentication Keys and tokens must stay server-side. Header name, OAuth flow, rotation and environment handling.
Response shape A binary response differs from JSON containing a URL. Content type, error body, download lifetime and checksum options.
Pricing Trial calls and low-resolution allowances are not production rates. Per-call price, included credits, overages and resolution tiers.
Data handling Uploaded images may contain personal or confidential information. Retention, deletion, regional processing and permitted uses.
Continuity Vendor changes can break an unattended integration. Status communication, versioning and migration commitments.

Adobe also publishes a Photoshop API remove-background operation, but the reviewed documentation does not establish current pricing, limits or precise availability. Check the Adobe Photoshop API reference directly.

Prepare images for more reliable cutouts

  • Send the original pixels when edge detail matters; resize only when the provider or your latency budget requires it.
  • Use a supported color mode and a real image MIME type. Do not label a WebP file as JPEG.
  • Strip accidental orientation inconsistencies by honoring EXIF orientation before display or post-processing.
  • Test hair, fur, thin cables, glass, smoke, shadows and low-contrast subjects separately. These cases expose edge behavior that a simple product photo will not.
  • Keep the original alongside the result so you can reprocess when your provider or settings change.

Post-process and validate the response

Check the HTTP status before writing bytes. Then validate the returned content type and image signature. A proxy, quota error or HTML error page can otherwise be saved with a .png extension.

from PIL import Image
from io import BytesIO

result = Image.open(BytesIO(response.content))
print(result.format, result.size, result.mode)
if "A" not in result.getbands():
    print("The output has no alpha channel; verify the requested format and provider behavior.")

For automated workflows, record the provider, request ID (when supplied), input hash, output hash, status code, elapsed time and retry count. Avoid logging API keys or the image itself.

Errors and fixes

Symptom Likely cause Fix
401 or 403 Missing, expired or incorrectly named credential. Check the required header, environment variable and key permissions. Rotate the key if it was exposed.
400 or 422 Wrong multipart field, unsupported format or malformed URL. Use the documented field name (image_file for the Photoroom example), send a valid MIME type and verify the source.
413 Request exceeds the provider’s byte or pixel limit. Resize or recompress within your quality target, then retry only after checking the new dimensions.
429 Rate or credit limit reached. Apply exponential backoff with jitter, cap concurrency, and inspect your plan’s limits before retrying.
5xx or timeout Temporary provider failure, slow upload or large image. Use a bounded timeout, retry idempotently with a request fingerprint, and place failed jobs on a queue.
HTML or JSON saved as an image Error response was written without checking status. Check response.ok, content type and the first bytes before saving.
Jagged or missing edges Subject blends into the background, contains fine detail or is partially occluded. Test representative samples, preserve adequate resolution and add a human-review path for low-confidence results.
Transparency appears black or white Your viewer or output format does not display alpha as expected. Inspect the alpha channel and use a format and renderer that support transparency.

Retries, queues and idempotency

  1. Generate a stable job ID from your own record, not from a retry counter.
  2. Store the original or a durable reference before calling the provider.
  3. Retry only transient failures such as network errors, 429 and selected 5xx responses.
  4. Use exponential backoff with a maximum attempt count. Do not retry authentication or validation errors.
  5. Write the result atomically and mark the job complete only after image validation succeeds.

If a provider does not offer idempotency keys, your job ID and output hash can prevent duplicate downstream work. You still need to account for a provider processing a request successfully while your client times out.

Performance and cost planning

  • Upload time: image bytes and network distance often dominate small requests. Compress within the quality required by your edge cases.
  • Concurrency: a worker queue lets you respect provider rate limits and prevents a traffic spike from exhausting credits.
  • Caching: hash the original bytes and relevant options. Reuse a prior result when the same input and settings are requested.
  • Monitoring: track success rate, p50/p95 latency, bytes uploaded, provider status codes and cost per completed image.
  • Budgeting: multiply expected production calls by the current per-call price, then account for retries, test traffic and higher-resolution tiers.

Photoroom lists the Remove Background API at $0.02 per call and says new accounts receive 10 free production calls. Treat both figures as changeable and verify its current pricing page before publishing a budget. remove.bg’s advertised free allowance is for low-resolution calls, not a universal production quota.

Provider continuity and privacy checks

Review retention and deletion terms before sending customer, medical, identity or unreleased product images. If policy requires it, remove metadata, encrypt stored originals and restrict access to generated cutouts.

remove.bg says its background-removal functionality is migrating into Canva and that, starting December 1, 2026, the functionality moves to Leonardo.Ai, also part of Canva. Verify the vendor’s current migration instructions and continuity terms before building a new long-lived integration. Read the migration FAQ.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, so it does not remove photographic backgrounds. It is useful when the asset you need is a clean rendering of a web page rather than a transparent subject cutout. One GET request returns PNG, JPEG, WebP or PDF, and its cleanup steps can accept consent banners and remove more than 60 known consent platforms, newsletter popups and chat widgets before capture.

See the ScreenshotNeo API documentation for all options. A minimal request is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf tools for AI agents. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Can I remove a background entirely in the browser?

You can, but a server-side API keeps credentials private and makes processing consistent across clients. Upload from your backend unless the provider explicitly supports a safe browser flow.

Which API produces the best cutouts?

The available research does not establish a universal quality winner. Test representative images, especially hair, transparent objects and fine product details, before choosing.

Should I use PNG for every result?

Use PNG when you need an alpha channel and lossless edges. Choose JPEG or WEBP when your delivery pipeline does not need transparency and smaller files are more important.

How should I handle a provider migration?

Pin the documented API version, monitor provider notices, keep an adapter around your provider-specific request, and verify continuity terms before committing new production traffic.

Is background removal the same as image matting?

Background removal usually means generating a foreground mask and exporting the subject. Matting can preserve semi-transparent edge details such as hair or glass; confirm what the selected API returns and validate alpha quality on your images.