RemBG 배경 제거 API – 개발자 문서 및 통합 가이드
전체 API 살펴보기 - 브라우저에서 실제 요청 실행
모든 엔드포인트, 매개변수 및 응답을 찾아보세요. API 키로 요청을 시도한 다음 언제든지 /api/openapi에서 원시 사양을 가져옵니다.
대화형 참조 실행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") |
환경 설정: API 키가 포함된 프로젝트 루트에 .env 파일이 있는지 확인하세요.
필요한 모듈 가져오기: 환경 변수를 처리하기 위해 @remove-ground-ai/rembg.js 및 dotenv 모듈에서 rembg 함수를 가져오는 것으로 시작하세요.
진행 콜백 구성: 라이브러리는 파일 작업의 진행 상황을 추적하기 위해 onDownloadProgress 및 onUploadProgress 콜백을 제공합니다. 제공된 예에서는 이러한 이벤트를 콘솔에 직접 기록합니다.
이제 샘플 사용법을 자세히 살펴보겠습니다.
// 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();
});
배경 제거 후 디스크에서 처리된 이미지를 제거하려는 경우 정리 함수를 호출할 수 있다는 점을 기억하세요.
진행률 표시줄 표시
백그라운드 제거 서비스를 통합할 때 사용자에게 업로드 또는 다운로드 요청 진행 상황에 대한 피드백을 제공하는 것이 유용한 경우가 많습니다. 이를 용이하게 하기 위해 자체 onDownloadProgress 및 onUploadProgress 콜백을 정의할 수 있습니다. 이 두 콜백 모두 AxiosProgressEvent를 이벤트 매개변수로 받아들입니다. 요청이 진행됨에 따라 이러한 콜백은 여러 번 호출되므로 진행률 표시줄을 표시하고 진행률에 따라 길이를 조정할 수 있습니다.
(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)
멤버십 및 크레딧 사용
요금제 라벨, 포함 및 선불 크레딧 잔액, 사용량을 반환합니다. UTC 달력 월(레거시), Stripe 정렬 청구 기간(갱신을 통한 모니터링)을 기준으로 쿼리하거나 알려진 청구 기간을 나열할 수 있습니다. API 키로만 인증하세요.
스키마, 예제 및 체험 콘솔은 전체 참조에서 동일한 엔드포인트를 확인하세요. 오픈 API 문서
엔드포인트
GET https://www.rembg.com/api/membership-usage인증
API 키를 보냅니다: x-api-key 헤더: YOUR_API_KEY_HERE(rembg.com의 프로필에서 키를 생성하고 관리하세요).
쿼리 매개변수
| 매개변수 | 유형 | 설명 |
|---|---|---|
| year | number | 역년(1~9999). 월을 사용하면 Redis 키 user:{uid}:app_usage:{year}:{month}를 읽습니다. 생략하면(그리고 periodStartUnix가 사용되지 않음) 기본값은 현재 UTC 연도입니다. |
| month | number (1–12) | 달력 월 1~12(키에 사용되는 UTC 규칙) 생략하면 기본값은 현재 UTC 월입니다. |
| periodStartUnix | number | Unix 타임스탬프(초): 청구 기간이 시작됩니다. 사용자:{uid}:app_usage:cycle:{기간StartUnix} 및 api_usage:cycle:…을 읽습니다. 연도 또는 월과 결합할 수 없습니다. |
| expand | string | 쉼표로 구분된 플래그입니다. billingCycle 객체를 추가하려면 billing_cycle을 포함하세요. billing_기간_*이 Redis에 존재할 경우 현재 스트라이프 기간이고, 그렇지 않으면 현재 UTC 달력 월입니다. 또한 특정 창에 대해 periodStartUnix와 함께 작동합니다. |
| includeBillingCycle | 1 / true | billing_cycle을 포함하는 확장과 동일합니다. billingCycle 객체를 포함하려면 1 또는 true로 설정하세요. |
| listBillingCycles | 1 / true | 전용 모드: listBillingCycles=1 또는 true는 { billingCycles: [...] }만 반환합니다. 이 사용자의 순환 키를 찾기 위해 Redis를 스캔합니다. 이 요청에서는 다른 쿼리 매개변수가 무시됩니다. |
연도 또는 월과 함께 periodStartUnix를 전달하지 마십시오. API는 400을 반환합니다. listBillingCycles 모드는 별개이며 다른 매개변수를 무시합니다.
청구 기간 나열
이를 사용하여 과거 및 현재 구독 창의 드롭다운을 채웁니다(각 항목은 periodStartUnix=…로 다시 전달할 수 있는 periodStartUnix입니다). 기간 종료 시간이 추론됩니다(다음 기간 시작 - 1 또는 활성 기간에 대한 스트라이프 current_기간_end).
curl --location 'https://www.rembg.com/api/membership-usage?listBillingCycles=1' \ --header 'x-api-key: YOUR_API_KEY_HERE'
응답 예시
{
"billingCycles": [
{
"periodStartUnix": 1774268612,
"periodEndUnix": 1776947012,
"appUsage": 120,
"apiUsage": 880
}
]
}최신 기간을 먼저 정렬했습니다. 주기 사용 키가 있거나 Stripe 웹후크의 현재 billing_기간_시작인 경우 기간이 나타납니다.
billingCycle 개체
확장에 billing_cycle이 포함되거나 includeBillingCycle이 설정된 경우 표시됩니다. 갱신 경계, 기간 내 사용량, 남은 포함 크레딧 등 대시보드에 사용하세요.
| 필드 | 설명 |
|---|---|
| periodStartUnix | 청구 기간의 시작(유닉스 초)입니다. 계정이 동기화되면 Stripe current_period_start와 일치합니다. |
| periodEndUnix | 현재 기간(unix 초)의 끝, 즉 다음 갱신 직전 — 동기화될 때 current_기간_end를 스트라이프합니다. 구독 취소 날짜와 동일하지 않습니다. |
| appUsage / apiUsage | 이 창에서 계산된 포함 크레딧 사용량: 웹/편집기(앱) 및 API 키(api). UsedIncludedCredits는 해당 합계와 같습니다. |
| includedCredits | Redis에 저장된 포함된 (계획) 크레딧 허용량(최상위 크레딧과 동일한 아이디어) |
| prepaidCredits | 선불(구매) 잔액; 각 청구 기간을 재설정하지 않습니다. |
| usedIncludedCredits | 창에 포함된 총 사용량(앱 + API)입니다. 선불 소비는 여기에 추가되지 않습니다. |
| remainingIncludedCredits | max(0, includeCredits − UsedIncludedCredits)입니다. |
| stripeBillingSynced | Redis가 Stripe의 billing_기간_시작/종료를 가져서 기간이 구독과 일치하면 true입니다. false는 API가 이 블록에 대해 UTC 달력 월로 대체되었음을 의미합니다. |
Stripe 웹후크가 사용자에 대한 청구 기간을 기록할 때까지 StripeBillingSynced는 false일 수 있으며 billingCycle 창은 UTC 달력 월을 따릅니다. 동기화 후 이미지 API의 사용 제한은 동일한 주기 키에 맞춰 조정됩니다.
'다음 갱신 전에 사용되는 크레딧'의 경우 확장=billing_cycle을 호출하고 billingCycle.기간EndUnix를 갱신 경계로 사용하고 billingCycle.usedIncludedCredits(또는 appUsage + apiUsage) 및 billingCycle.remainingIncludedCredits를 사용합니다. 총 일회용 잔액을 원할 경우 prepaidCredits를 추가하세요.
예(cURL)
특정 UTC 월의 사용량
curl --location 'https://www.rembg.com/api/membership-usage?year=2026&month=3' \ --header 'x-api-key: YOUR_API_KEY_HERE'
현재 결제 주기 + 전체 결제 주기 차단(동기화 시 갱신 정렬)
# 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'
기간 시작별 하나의 과거 청구 창(listBillingCycles 또는 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'
JSON 예(결제 주기 포함)
최상위 app_usage 및 api_usage는 항상 요청된 월 또는 periodStartUnix가 설정된 경우 해당 주기의 카운터를 반영합니다. Expand=billing_cycle을 생략하면 billingCycle이 없습니다.
{
"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
}
}StripeBillingSynced가 true인 경우 billingCycle은 백그라운드 제거 API 시행과 일치합니다. false인 경우 월별 필드를 사용하거나 Webhook가 Redis에서 billing_기간_*을 채울 때까지 기다립니다.
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