RemBG 后台删除 API – 开发人员文档和集成指南






OpenAPI · 现场游乐场

探索完整的 API - 在浏览器中运行真实请求

浏览每个端点、参数和响应。使用您的 API 密钥尝试请求,然后随时在 /api/openapi 获取原始规范。

启动交互式参考

安装 rembg.js

latest npm versionGitHub starsnpm downloadslicenseGitHub issues

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
ParameterTypeRequiredDefaultDescription
apiKeystring
Required

Your Rembg API key
inputImagestring | 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.formatwebp (default) | png
Optional
webp
Specifies the output image format. Either "webp" (default) or "png"
options.returnBase64boolean
Optional
false
Return Base64 string instead of file
options.returnMaskboolean
Optional
false
Return only the alpha mask
options.wnumber
Optional

Target width (maintains aspect ratio)
options.hnumber
Optional

Target height (maintains aspect ratio)
options.exact_resizeboolean
Optional
false
Force exact width × height (may distort)
options.anglenumber
Optional
0
Rotation angle in degrees
options.expandboolean
Optional
true
Add padding so rotated images aren’t cropped
options.bg_colorstring
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
					

会员资格和积分使用

返回您的计划标签、包含的和预付的积分余额以及使用情况。您可以按 UTC 日历月(旧版)、按 Stripe 对齐的计费周期(用于通过续订进行监控)进行查询,或列出已知的计费周期。仅使用您的 API 密钥进行身份验证。

有关架构、示例和试用控制台,请参阅完整参考中的相同端点: 打开 API 文档

端点
GET https://www.rembg.com/api/membership-usage
身份验证

发送您的 API 密钥: header x-api-key: YOUR_API_KEY_HERE(在 rembg.com 上的个人资料中创建和管理密钥)。

查询参数
参数输入说明
yearnumber日历年 (1–9999)。对于月份,读取 Redis 密钥 user:{uid}:app_usage:{year}:{month}。如果省略(且不使用 periodStartUnix),则默认为当前 UTC 年份。
monthnumber (1–12)日历月 1–12(用于键的 UTC 约定)。如果省略,则默认为当前 UTC 月份。
periodStartUnixnumberUnix 时间戳(以秒为单位):计费窗口的开始。读取 user:{uid}:app_usage:cycle:{periodStartUnix} 和 api_usage:cycle:...。不能与年份或月份组合。
expandstring以逗号分隔的标志。包含 billing_cycle 以添加 billingCycle 对象:当 billing_period_* 存在于 Redis 中时,当前 Stripe 周期,否则当前 UTC 日历月。也适用于特定窗口的 periodStartUnix。
includeBillingCycle1 / true与扩展包含 billing_cycle 相同:设置为 1 或 true 以包含 billingCycle 对象。
listBillingCycles1 / true专用模式:listBillingCycles=1 或 true 仅返回 { billingCycles: [...] }。扫描 Redis 查找该用户的循环密钥;此请求将忽略其他查询参数。

不要将 periodStartUnix 与年或月一起传递 — API 返回 400。listBillingCycles 模式是独立的,并忽略其他参数。

列出结算周期

使用它来填充过去和当前订阅窗口的下拉列表(每个条目都是一个 periodStartUnix,您可以使用 periodStartUnix=... 传回)。推断周期结束时间(下一个周期开始 - 1,或活动周期的 Stripe 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 webhooks 的当前 billing_period_start,则会出现句点。

billingCycle 对象

当设置 Expand Includes billing_cycle 或 includeBillingCycle 时出现。将其用于仪表板:续订边界、窗口中的使用情况以及剩余的包含积分。

字段说明
periodStartUnix计费窗口开始(unix 秒)。帐户同步时与 Stripe current_period_start 匹配。
periodEndUnix当前窗口结束(unix 秒),即在下一次更新之前 — 同步时条带 current_period_end。与订阅取消日期不同。
appUsage / apiUsage此窗口中计算的包含积分使用量:网络/编辑器(应用程序)与 API 密钥 (api)。 usedIncludedCredits 等于它们的总和。
includedCredits您包含的(计划)信用额度存储在 Redis 中(与顶级信用额度相同)。
prepaidCredits预付(购买)余额;不重置每个计费周期。
usedIncludedCredits窗口中包含的总使用量(应用程序 + API)。这里不添加预付费消费。
remainingIncludedCreditsmax(0,includedCredits −usedIncludedCredits)。
stripeBillingSyncedtrue,因此窗口与您的订阅相匹配; false 表示 API 回退到该区块的 UTC 日历月。

在 Stripe webhook 为用户写入计费周期之前,stripeBillingSynced 可能为 false,并且 billingCycle 窗口遵循 UTC 日历月。同步后,图像 API 的使用限制与相同的周期密钥一致。

对于“下次续订前使用的积分”,请使用 Expand=billing_cycle 进行调用,并使用 billingCycle.periodEndUnix 作为续订边界、billingCycle.usedIncludedCredits(或 appUsage + apiUsage)和 billingCycle.remainingIncludedCredits。如果您想要总的可支配余额,请添加预付积分。

示例 (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'

按周期开始的一个历史计费窗口(来自 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.

Single Error Response

HTTP/1.1 400 Bad Request

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "Image width (12000px) exceeds the maximum allowed width of 10000px.",
  "field": "image",
  "status": 400
}

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
ScenarioStatusError 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 error field for the error message
  • Check for the details array when handling multiple validation errors
  • Use the field property to map errors to specific request parameters