RemBG API za uklanjanje pozadine – dokumenti za razvojne programere i vodič za integraciju
Istražite cijeli API—pokrenite stvarne zahtjeve u svom pregledniku
Pregledajte svaku krajnju točku, parametre i odgovore. Isprobajte zahtjeve sa svojim API ključem, a zatim zgrabite sirovu specifikaciju na /api/openapi bilo kada.
Pokreni interaktivnu referencuInstalacija rembg.js
npm i @remove-background-ai/rembg.js
API Reference for rembg.js
@remove-background-ai/rembg.js is a zero-config Node.js wrapper for the free Rembg API, enabling background removal with simple, customizable parameters.
Parameters for RemBG.js
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| apiKey | string | Required | – | Your Rembg API key |
| inputImage | string | Buffer | { base64: string } | Required | – | Image file, buffer, or base64 payload |
| onDownloadProgress | (event) => void | Optional | – | Hook for upload progress events |
| onUploadProgress | (event) => void | Optional | – | Hook for download progress events |
| options.format | webp (default) | png | Optional | webp | Specifies the output image format. Either "webp" (default) or "png" |
| options.returnBase64 | boolean | Optional | false | Return Base64 string instead of file |
| options.returnMask | boolean | Optional | false | Return only the alpha mask |
| options.w | number | Optional | – | Target width (maintains aspect ratio) |
| options.h | number | Optional | – | Target height (maintains aspect ratio) |
| options.exact_resize | boolean | Optional | false | Force exact width × height (may distort) |
| options.angle | number | Optional | 0 | Rotation angle in degrees |
| options.expand | boolean | Optional | true | Add padding so rotated images aren’t cropped |
| options.bg_color | string | Optional | - | Optional solid background color in hex (e.g. #FFFFFFFF) or named color (e.g. "red", "blue") |
Postavljanje vašeg okruženja: Provjerite imate li .env datoteku u korijenu projekta koja sadrži vaš API ključ.
Uvoz potrebnih modula: Započnite uvozom funkcije rembg iz @remove-background-ai/rembg.js i modula dotenv za rukovanje varijablama okruženja.
Konfiguriranje povratnih poziva napretka: Knjižnica nudi povratne pozive onDownloadProgress i onUploadProgress za praćenje napretka operacija datoteka. U navedenom primjeru te događaje bilježimo izravno na konzolu.
Sada, pogledajmo pobliže primjer upotrebe:
// script.mjs file
import { rembg } from '@remove-background-ai/rembg.js';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
// API_KEY will be loaded from the .env file
const API_KEY = process.env.API_KEY;
// log upload and download progress
const onDownloadProgress = console.log;
const onUploadProgress = console.log;
rembg({
apiKey: API_KEY,
inputImage: './input.png', //inputImage can be one of these: string | Buffer | { base64: string };
onDownloadProgress,
onUploadProgress
}).then(({ outputImagePath, cleanup }) => {
console.log('✅🎉 background removed and saved under path=', outputImagePath);
// if called, it will cleanup (remove from disk) your removed background image
// cleanup();
});
Imajte na umu da se funkcija čišćenja može pozvati ako želite ukloniti obrađenu sliku s diska nakon uklanjanja pozadine.
Prikaz trake napretka
Kada integrirate uslugu uklanjanja pozadine, često je korisno korisnicima dati povratne informacije o tijeku njihovog zahtjeva za učitavanje ili preuzimanje. Da biste to olakšali, možete definirati vlastite povratne pozive onDownloadProgress i onUploadProgress. Oba ova povratna poziva prihvaćaju AxiosProgressEvent kao parametar događaja. Kako se zahtjev nastavlja, ovi se povratni pozivi pozivaju više puta, što vam omogućuje da, na primjer, prikažete traku napretka i prilagodite njezinu duljinu na temelju napretka.
(base) root@DESKTOP-C0Q8KK7:~/rembg.js-test# node index.mjs
{
loaded: 65687,
total: 68474,
progress: 0.9592984198381868, <---- @95% progress
bytes: 65687,
rate: undefined,
estimated: undefined,
upload: true <---- upload progress
}
{
loaded: 68474,
total: 68474,
progress: 1, <---- @100% progress
bytes: 2787,
rate: undefined,
estimated: undefined,
upload: true <---- upload progress
}
{
loaded: 1002,
total: 68824,
progress: 0.014558874811112402, <---- @1% progress
bytes: 1002,
rate: undefined,
estimated: undefined,
download: true <---- download progress
}
{
loaded: 68824,
total: 68824,
progress: 1, <---- @100% progress
bytes: 67822,
rate: undefined,
estimated: undefined,
download: true <---- download progress
}
✅🎉 background removed and saved under path=/tmp/rembg--3339-DBqqeJ2eOs4D-.png
Curl
# Full example: upload an image and remove its background with all optional parameters curl -X POST "https://api.rembg.com/rmbg" -H "x-api-key: YOUR_API_KEY_HERE" # your personal API key -F "image=@/path/to/image.jpg" # input image file -F "format=webp" # output format: webp (default) or png -F "w=800" # target width in pixels (maintains aspect ratio unless exact_resize=true) -F "h=600" # target height in pixels -F "exact_resize=false" # true = force exact w × h, may distort -F "mask=false" # true = return only the alpha mask instead of full image -F "bg_color=#ffffffff" # optional solid background color (RGBA hex) -F "angle=0" # rotate the image by given degrees after processing -F "expand=true" # add padding so rotated images don’t get cropped
HTTP
POST /rmbg HTTP/1.1
Host: api.rembg.com
x-api-key: YOUR_API_KEY_HERE
Content-Type: multipart/form-data; boundary=----BOUNDARY
------BOUNDARY
Content-Disposition: form-data; name="image"; filename="image.jpg"
Content-Type: image/jpeg
<binary data of your image goes here>
------BOUNDARY
Content-Disposition: form-data; name="format"
webp
------BOUNDARY
Content-Disposition: form-data; name="w"
800
------BOUNDARY
Content-Disposition: form-data; name="h"
600
------BOUNDARY
Content-Disposition: form-data; name="exact_resize"
false
------BOUNDARY
Content-Disposition: form-data; name="mask"
false
------BOUNDARY
Content-Disposition: form-data; name="bg_color"
#ffffffff
------BOUNDARY
Content-Disposition: form-data; name="angle"
0
------BOUNDARY
Content-Disposition: form-data; name="expand"
true
------BOUNDARY--
Python Requests
import requests
# Endpoint URL for the background-removal API
url = "https://api.rembg.com/rmbg"
# Required API key header
headers = {
"x-api-key": "YOUR_API_KEY_HERE"
}
# The image file to process (opened in binary mode)
files = {
"image": open("/path/to/image.jpg", "rb")
}
# Optional form fields supported by your backend.
# Adjust values as needed; any of these can be omitted.
data = {
"format": "webp", # Output format: "webp" (default) or "png"
"w": 800, # Target width (maintains aspect ratio unless exact_resize is true)
"h": 600, # Target height
"exact_resize": "false", # "true" forces exact w×h, may distort
"mask": "false", # "true" returns only the alpha mask
"bg_color": "#ffffffff", # Optional solid background color (RGBA hex)
"angle": 0, # Rotation angle in degrees
"expand": "true", # Add padding so rotated images aren’t cropped
}
# Send the POST request with headers, file, and extra form data
response = requests.post(url, headers=headers, files=files, data=data)
# Handle the response
if response.status_code == 200:
# Save the processed image to disk
with open("output.webp", "wb") as f:
f.write(response.content)
print("Background removed successfully → saved as output.webp")
else:
# Print error details if the request failed
print("Error:", response.status_code, response.text)
Članstvo i korištenje kredita
Vraća oznaku vašeg plana, uključena i unaprijed plaćena stanja kredita i korištenje. Možete postavljati upite prema UTC kalendarskom mjesecu (naslijeđeno), prema Stripe-aligniranom obračunskom razdoblju (za praćenje kroz obnovu) ili popisu poznatih obračunskih razdoblja. Autentificirajte se samo svojim API ključem.
Za sheme, primjere i konzolu za isprobavanje pogledajte istu krajnju točku u punoj referenci: Open API dokumenti
Krajnja točka
GET https://www.rembg.com/api/membership-usageAutentifikacija
Pošaljite svoj API ključ: zaglavlje x-api-ključ: YOUR_API_KEY_OVDJE (stvorite i upravljajte ključevima u svom profilu na rembg.com).
Parametri upita
| Parametar | Vrsta | Opis |
|---|---|---|
| year | number | Kalendarska godina (1–9999). Uz mjesec, čita Redis ključeve user:{uid}:app_usage:{year}:{month}. Ako se izostavi (i periodStartUnix se ne koristi), zadana je trenutna UTC godina. |
| month | number (1–12) | Kalendarski mjesec 1–12 (za ključeve se koristi UTC konvencija). Ako je izostavljeno, zadano je trenutni UTC mjesec. |
| periodStartUnix | number | Unix vremenska oznaka u sekundama: početak prozora naplate. Čita korisnika:{uid}:app_usage:cycle:{periodStartUnix} i api_usage:cycle:…. Ne može se kombinirati s godinom ili mjesecom. |
| expand | string | Oznake odvojene zarezima. Uključite billing_cycle da biste dodali objekt billingCycle: trenutno Stripe razdoblje kada billing_period_* postoji u Redisu, inače trenutni UTC kalendarski mjesec. Također radi s periodStartUnixom za određeni prozor. |
| includeBillingCycle | 1 / true | Isto kao proširenje koje sadrži billing_cycle: postavite na 1 ili true da uključite objekt billingCycle. |
| listBillingCycles | 1 / true | Namjenski način rada: listBillingCycles=1 ili true vraća samo { billingCycles: [...] }. Skenira Redis za ključeve ciklusa za ovog korisnika; ostali parametri upita zanemaruju se na ovom zahtjevu. |
Ne prosljeđujte periodStartUnix zajedno s godinom ili mjesecom — API vraća 400. Način rada listBillingCycles je odvojen i zanemaruje druge parametre.
Popis obračunskih razdoblja
Koristite ovo za popunjavanje padajućeg izbornika prošlih i trenutnih prozora pretplate (svaki unos je periodStartUnix koji možete vratiti s periodStartUnix=…). Zaključuju se vremena završetka razdoblja (početak sljedećeg razdoblja − 1 ili Stripe current_period_end za aktivno razdoblje).
curl --location 'https://www.rembg.com/api/membership-usage?listBillingCycles=1' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Primjer odgovora
{
"billingCycles": [
{
"periodStartUnix": 1774268612,
"periodEndUnix": 1776947012,
"appUsage": 120,
"apiUsage": 880
}
]
}Prvo sortirano najnovije razdoblje. Razdoblje se pojavljuje ako postoji ključ za korištenje ciklusa ili ako je to trenutni billing_period_start iz Stripe webhooks.
Objekt billingCycle
Prisutno kada je proširenje uključeno u billing_cycle ili includeBillingCycle postavljeno. Koristite ga za nadzorne ploče: granica obnove, korištenje u prozoru i preostali uključeni krediti.
| Polje | Opis |
|---|---|
| periodStartUnix | Početak prozora naplate (unix sekunde). Odgovara Stripe current_period_start kada je račun sinkroniziran. |
| periodEndUnix | Kraj trenutnog prozora (unix sekunde), tj. neposredno prije sljedeće obnove — Stripe current_period_end kada se sinkronizira. Nije isto što i datum otkazivanja pretplate. |
| appUsage / apiUsage | Korištenje uključenog kredita broji se u ovom prozoru: web/uređivač (aplikacija) u odnosu na API ključ (api). usedIncludedCredits jednak je njihovom zbroju. |
| includedCredits | Vaše uključeno (plansko) odobrenje kredita kako je pohranjeno u Redisu (ista ideja kao i krediti najviše razine). |
| prepaidCredits | Pretplaćeni (kupljeni) saldo; ne poništava svako obračunsko razdoblje. |
| usedIncludedCredits | Ukupna uključena upotreba u prozoru (aplikacija + API). Ovdje se ne dodaje prepaid potrošnja. |
| remainingIncludedCredits | max(0, includedCredits − usedIncludedCredits) za ovu snimku. |
| stripeBillingSynced | true kada Redis ima billing_period_start/end od Stripea tako da prozor odgovara vašoj pretplati; false znači da se API vratio na UTC kalendarski mjesec za ovaj blok. |
Sve dok Stripe webhooks ne zapiše razdoblja naplate za korisnika, stripeBillingSynced može biti false, a prozor billingCycle slijedi UTC kalendarski mjesec. Nakon sinkronizacije, ograničenja upotrebe na API-ju slike usklađuju se s istim ključevima ciklusa.
Za “kredite iskorištene prije sljedeće obnove”, pozovite s expand=billing_cycle i koristite billingCycle.periodEndUnix kao granicu obnove, billingCycle.usedIncludedCredits (ili appUsage + apiUsage) i billingCycle.remainingIncludedCredits. Dodajte prepaidCredits ako želite ukupni raspoloživi saldo.
Primjeri (cURL)
Upotreba za određeni UTC kalendarski mjesec
curl --location 'https://www.rembg.com/api/membership-usage?year=2026&month=3' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Trenutačni ciklus naplate + cijeli blok ciklusa naplate (obnova usklađena kada se sinkronizira)
# Current subscription window + usage (renewal-aligned when Stripe is synced) curl --location 'https://www.rembg.com/api/membership-usage?expand=billing_cycle' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Jedan povijesni period naplate po početku razdoblja (s liste BillingCycles ili Stripe)
# Specific billing period by Stripe period start (unix seconds) curl --location 'https://www.rembg.com/api/membership-usage?periodStartUnix=1774268612&expand=billing_cycle' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Primjer JSON (s ciklusom naplate)
App_usage i api_usage najviše razine uvijek odražavaju traženi kalendarski mjesec ili, kada je periodStartUnix postavljen, brojače tog ciklusa. Kada je expand=billing_cycle izostavljen, billingCycle je odsutan.
{
"membership": "Premium-20000",
"credits": 18500,
"prepaidCredits": 2000,
"app_usage": 8500,
"api_usage": 10000,
"billingCycle": {
"periodStartUnix": 1740441600,
"periodEndUnix": 1743033599,
"appUsage": 4200,
"apiUsage": 5100,
"includedCredits": 18500,
"prepaidCredits": 2000,
"usedIncludedCredits": 9300,
"remainingIncludedCredits": 9200,
"stripeBillingSynced": true
}
}Kada je stripeBillingSynced istinit, billingCycle odgovara provedbi na API-ju za uklanjanje pozadine. Kada je lažno, oslonite se na polja kalendarskog mjeseca ili pričekajte dok webdojavnici ne popune billing_period_* u Redisu.
Error Responses
All error responses return a JSON body with a status field matching the HTTP status code.
Multiple Validation Errors Response
HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Multiple validation errors",
"details": [
{ "field": "w", "message": "'w' must be an integer, got: 'abc'" },
{ "field": "angle", "message": "'angle' must be between -360 and 360 degrees, got: 500.0" }
],
"status": 400
}Error Reference
| Scenario | Status | Error Message |
|---|---|---|
| No image provided | 400 | No image file provided. Please include an 'image' field in your form data. |
| No file selected | 400 | No file selected. Please choose an image file to upload. |
| Unsupported file type | 400 | File type '.exe' is not supported. Allowed formats: webp, bmp, png, jpg, jpeg |
| Corrupt image | 400 | File does not appear to be a valid image (invalid file signature) |
| Empty file (0 bytes) | 400 | Uploaded file is empty (0 bytes). |
| File too large | 400 | File size (55.2 MB) exceeds the maximum allowed size of 50 MB. |
| Image too wide | 400 | Image width (12000px) exceeds the maximum allowed width of 10000px. |
| Image too tall | 400 | Image height (15000px) exceeds the maximum allowed height of 10000px. |
| Bad w or h value | 400 | 'w' must be an integer, got: 'abc' |
| w or h out of range | 400 | 'w' must be at least 1, got: -5 |
| w or h above max | 400 | 'w' must be at most 10000, got: 15000 |
| Bad angle | 400 | 'angle' must be a number, got: 'ninety' |
| Angle out of range | 400 | 'angle' must be between -360 and 360 degrees, got: 500.0 |
| Bad output format | 400 | Invalid format 'gif'. Allowed formats: PNG, JPEG, WEBP, BMP |
| Bad bg_color | 400 | Invalid color format '#12345'. Use hex format: #RGB, #RGBA, #RRGGBB, or #RRGGBBAA |
| mask + bg_color conflict | 400 | Cannot use 'mask=true' together with 'bg_color'. Choose one or the other. |
| Email not verified | 403 | Email address not verified – please check your inbox |
| Invalid API key | 401 | invalid api key |
| Both API key and user token sent | 400 | This is a mistake: Cannot use both API key and user token |
| Rate limit exceeded (short-term) | 429 | You're making requests too quickly, Please Upgrade or slow down. |
| Rate limit exceeded (daily, anonymous) | 429 | You've reached your daily limit. Please sign up for more access. |
| Rate limit exceeded (monthly, authenticated) | 429 | You've reached your monthly limit. Consider purchasing more credits. |
Error Handling Guidelines
- Check HTTP status code 400 to identify validation errors
- Parse the
errorfield for the error message - Check for the
detailsarray when handling multiple validation errors - Use the
fieldproperty to map errors to specific request parameters