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-background-ai/rembg.js から rembg 関数と dotenv モジュールをインポートして環境変数を処理することから始めます。
進行状況コールバックの構成: このライブラリは、ファイル操作の進行状況を追跡するための 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 キーを送信します: header x-api-key: YOUR_API_KEY_HERE (rembg.com のプロファイルでキーを作成および管理します)。
クエリパラメータ
| パラメータ | 説明 | |
|---|---|---|
| year | number | 暦年 (1 ~ 9999)。 month の場合、Redis キー user:{uid}:app_usage:{year}:{month} を読み取ります。省略した場合 (および periodStartUnix が使用されていない場合)、デフォルトは現在の UTC 年になります。 |
| month | number (1–12) | 暦月 1 ~ 12 (キーには UTC 規則が使用されます)。省略した場合、デフォルトは現在の UTC 月になります。 |
| periodStartUnix | number | 秒単位の Unix タイムスタンプ: 請求期間の開始。 user:{uid}:app_usage:cycle:{periodStartUnix} および api_usage:cycle:… を読み取ります。年や月と組み合わせることはできません。 |
| expand | string | カンマ区切りのフラグ。 billing_cycle オブジェクトを追加するには、billing_cycle を含めます。Billing_period_* が Redis に存在する場合は現在の Stripe 期間、それ以外の場合は現在の 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_period_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 Webhook からの現在の billing_period_start である場合、期間が表示されます。
billingCycle オブジェクト
Expand include billing_cycle または includeBillingCycle が設定されている場合に存在します。ダッシュボードに使用します: 更新境界、ウィンドウ内での使用状況、および残りの含まれているクレジット。
| フィールド | 説明 |
|---|---|
| periodStartUnix | 請求期間の開始 (UNIX 秒)。アカウントが同期されるときに、Stripe current_period_start と一致します。 |
| periodEndUnix | 現在のウィンドウの終わり (UNIX 秒)、つまり次の更新の直前 — 同期時に current_period_end をストライプ化します。定期購入のキャンセル日とは異なります。 |
| appUsage / apiUsage | このウィンドウでカウントされる含まれるクレジットの使用量: Web/エディター (アプリ) と API キー (API)。 usedIncludedCredits はそれらの合計と等しくなります。 |
| includedCredits | Redis に保存されている含まれる (プランの) クレジット許容量 (トップレベルのクレジットと同じ考え方)。 |
| prepaidCredits | プリペイド (購入) 残高。各請求期間はリセットされません。 |
| usedIncludedCredits | ウィンドウ内の合計使用量 (アプリ + API)。プリペイド消費はここでは加算されません。 |
| remainingIncludedCredits | このスナップショットの max(0, IncludedCredits − usedIncludedCredits)。 |
| stripeBillingSynced | Redis が Stripe からの billing_period_start/end を持っているため、期間がサブスクリプションと一致する場合は true。 false は、API がこのブロックに対して UTC 暦月にフォールバックしたことを意味します。 |
Stripe Webhook がユーザーの請求期間を書き込むまで、 StripeBillingSynced は false になる可能性があり、billingCycle ウィンドウは UTC 暦月に従います。同期後、イメージ API の使用制限は同じサイクル キーに合わせて調整されます。
「次回の更新前に使用されるクレジット」の場合は、expand=billing_cycle を指定して呼び出し、更新境界として billingCycle.periodEndUnix、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'
現在の請求サイクル + 完全な billingCycle ブロック (同期時に更新に合わせて調整)
# 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'
期間開始ごとの 1 つの過去の請求期間 (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_period_* が設定されるまで待機します。
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