API xóa nền RemBG – Tài liệu dành cho nhà phát triển & Hướng dẫn tích hợp






OpenAPI · Sân chơi trực tiếp

Khám phá API đầy đủ—chạy các yêu cầu thực tế trong trình duyệt của bạn

Duyệt qua mọi điểm cuối, thông số và phản hồi. Hãy thử các yêu cầu bằng khóa API của bạn, sau đó lấy thông số thô tại /api/openapi bất cứ lúc nào.

Khởi chạy tài liệu tham khảo tương tác

Cài đặt 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")
  • Thiết lập môi trường của bạn: Đảm bảo bạn có tệp .env trong thư mục gốc dự án chứa khóa API của bạn.

  • Nhập các mô-đun cần thiết: Bắt đầu bằng cách nhập hàm rembg từ @remove-background-ai/rembg.js và mô-đun dotenv để xử lý các biến môi trường.

  • Định cấu hình lệnh gọi lại tiến trình: Thư viện cung cấp các lệnh gọi lại onDownloadProgress và onUploadProgress để theo dõi tiến trình hoạt động của tệp. Trong ví dụ được cung cấp, chúng tôi đang ghi nhật ký các sự kiện này trực tiếp vào bảng điều khiển.

Bây giờ, chúng ta hãy xem xét kỹ hơn cách sử dụng mẫu:


// 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();
});
					
						

Hãy nhớ rằng, chức năng dọn dẹp có thể được gọi nếu bạn muốn xóa hình ảnh đã xử lý khỏi đĩa của mình sau khi xóa nền.

Hiển thị thanh tiến trình

Khi tích hợp dịch vụ xóa nền, việc cung cấp cho người dùng phản hồi về tiến trình yêu cầu tải lên hoặc tải xuống của họ thường rất hữu ích. Để tạo điều kiện thuận lợi cho việc này, bạn có thể xác định các lệnh gọi lại onDownloadProgress và onUploadProgress của riêng mình. Cả hai lệnh gọi lại này đều chấp nhận AxiosProgressEvent làm thông số sự kiện. Khi yêu cầu tiếp tục, các lệnh gọi lại này được gọi nhiều lần, chẳng hạn như cho phép bạn hiển thị thanh tiến trình và điều chỉnh độ dài của thanh đó dựa trên tiến trình.


 (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
					

Cách sử dụng tư cách thành viên và tín dụng

Trả về nhãn gói của bạn, số dư tín dụng đã bao gồm và trả trước cũng như mức sử dụng. Bạn có thể truy vấn theo tháng theo lịch UTC (cũ), theo kỳ thanh toán được điều chỉnh theo Stripe (để theo dõi thông qua gia hạn) hoặc liệt kê các kỳ thanh toán đã biết. Chỉ xác thực bằng khóa API của bạn.

Để biết các lược đồ, ví dụ và bảng điều khiển dùng thử, hãy xem điểm cuối tương tự trong tài liệu tham khảo đầy đủ: Mở tài liệu API

Điểm cuối
GET https://www.rembg.com/api/membership-usage
Xác thực

Gửi khóa API của bạn: tiêu đề x-api-key: YOUR_API_KEY_HERE (tạo và quản lý khóa trong hồ sơ của bạn trên rembg.com).

Tham số truy vấn
Tham sốNhậpMô tả
yearnumberNăm dương lịch (1–9999). Với tháng, đọc khóa Redis user:{uid}:app_usage:{year}:{month}. Nếu bị bỏ qua (và PeriodStartUnix không được sử dụng), sẽ mặc định là năm UTC hiện tại.
monthnumber (1–12)Tháng 1–12 theo lịch (quy ước UTC được sử dụng cho khóa). Nếu bỏ qua, mặc định là tháng UTC hiện tại.
periodStartUnixnumberDấu thời gian Unix tính bằng giây: bắt đầu thời hạn thanh toán. Đọc user:{uid}:app_usage:cycle:{ PeriodStartUnix} và api_usage:cycle:…. Không thể kết hợp với năm hoặc tháng.
expandstringCờ được phân tách bằng dấu phẩy. Bao gồm Billing_cycle để thêm đối tượng BillingCycle: khoảng thời gian Stripe hiện tại khi Billing_ Period_* tồn tại trong Redis, nếu không thì tháng theo lịch UTC hiện tại. Cũng hoạt động với PeriodStartUnix cho một cửa sổ cụ thể.
includeBillingCycle1 / trueTương tự như mở rộng chứa Billing_cycle: đặt thành 1 hoặc true để bao gồm đối tượng BillingCycle.
listBillingCycles1 / trueChế độ chuyên dụng: listBillingCycles=1 hoặc true chỉ trả về { BillingCycles: [...] }. Quét Redis để tìm các khóa chu kỳ cho người dùng này; các tham số truy vấn khác bị bỏ qua trong yêu cầu này.

Không chuyển PeriodStartUnix cùng với năm hoặc tháng — API trả về 400. Chế độ listBillingCycles tách biệt và bỏ qua các thông số khác.

Liệt kê thời hạn thanh toán

Sử dụng mục này để điền danh sách thả xuống gồm các cửa sổ đăng ký trước đây và hiện tại (mỗi mục nhập là một PeriodStartUnix mà bạn có thể chuyển lại bằng PeriodStartUnix=…). Thời gian kết thúc kỳ được suy ra (thời điểm bắt đầu kỳ tiếp theo − 1 hoặc kết thúc kỳ_thời gian hiện tại cho giai đoạn hoạt động).

curl --location 'https://www.rembg.com/api/membership-usage?listBillingCycles=1' \
  --header 'x-api-key: YOUR_API_KEY_HERE'

Câu trả lời mẫu

{
  "billingCycles": [
    {
      "periodStartUnix": 1774268612,
      "periodEndUnix": 1776947012,
      "appUsage": 120,
      "apiUsage": 880
    }
  ]
}

Sắp xếp tiết mới nhất trước. Một khoảng thời gian sẽ xuất hiện nếu có khóa sử dụng chu kỳ hoặc nếu đó là Bill_ Period_start hiện tại từ webhook của Stripe.

Đối tượng BillingCycle

Xuất hiện khi mở rộng bao gồm chu kỳ thanh toán hoặc bao gồm chu kỳ thanh toán được đặt. Sử dụng nó cho trang tổng quan: ranh giới gia hạn, mức sử dụng trong cửa sổ và các khoản tín dụng được bao gồm còn lại.

TrườngMô tả
periodStartUnixBắt đầu khoảng thời gian thanh toán (giây unix). Khớp với Stripe current_ Period_start khi tài khoản được đồng bộ hóa.
periodEndUnixKết thúc cửa sổ hiện tại (giây unix), tức là ngay trước lần gia hạn tiếp theo — Sọc current_ Period_end khi được đồng bộ hóa. Không giống với ngày hủy đăng ký.
appUsage / apiUsageMức sử dụng tín dụng đi kèm được tính trong cửa sổ này: web/editor (ứng dụng) so với khóa API (api). usedIncludedCredits bằng tổng của chúng.
includedCreditsKhoản trợ cấp tín dụng (gói) được bao gồm của bạn được lưu trữ trong Redis (ý tưởng tương tự như các khoản tín dụng cấp cao nhất).
prepaidCreditsSố dư trả trước (đã mua); không thiết lập lại mỗi kỳ thanh toán.
usedIncludedCreditsTổng mức sử dụng được bao gồm trong cửa sổ (ứng dụng + API). Tiêu dùng trả trước không được thêm vào đây.
remainingIncludedCreditsmax(0, AddedCredits − usedIncludedCredits) cho ảnh chụp nhanh này.
stripeBillingSyncedđúng khi Redis có Billing_ Period_start/end từ Stripe để khoảng thời gian khớp với đăng ký của bạn; sai có nghĩa là API quay trở lại tháng theo lịch UTC cho khối này.

Cho đến khi webhook của Stripe ghi thời hạn thanh toán cho người dùng, sọcBillingSynced có thể sai và cửa sổ BillingCycle tuân theo tháng theo lịch UTC. Sau khi đồng bộ hóa, giới hạn sử dụng trên API hình ảnh sẽ căn chỉnh theo cùng một khóa chu trình.

Đối với “tín dụng được sử dụng trước lần gia hạn tiếp theo”, hãy gọi với Expand=billing_cycle và sử dụng BillingCycle. PeriodEndUnix làm ranh giới gia hạn, BillingCycle.usedIncludedCredits (hoặc appUsage + apiUsage) và BillingCycle.remainingIncludedCredits. Thêm Tín dụng trả trước nếu bạn muốn tổng số dư khả dụng.

Ví dụ (cURL)

Cách sử dụng cho một tháng theo lịch UTC cụ thể

curl --location 'https://www.rembg.com/api/membership-usage?year=2026&month=3' \
  --header 'x-api-key: YOUR_API_KEY_HERE'

Chu kỳ thanh toán hiện tại + khối Chu kỳ thanh toán đầy đủ (được căn chỉnh gia hạn khi được đồng bộ hóa)

# 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'

Một khoảng thời gian thanh toán lịch sử theo thời gian bắt đầu (từ danh sáchBillingCycles hoặc 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 mẫu (có chu kỳ thanh toán)

App_usage và api_usage cấp cao nhất luôn phản ánh tháng theo lịch được yêu cầu hoặc khi PeriodStartUnix được đặt, bộ đếm của chu kỳ đó. Khi bỏ qua Expand=billing_cycle, BillingCycle sẽ không xuất hiện.

{
  "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
  }
}

Khi sọcBillingSynced là đúng, BillingCycle khớp với việc thực thi trên API xóa nền. Khi sai, hãy dựa vào các trường tháng theo lịch hoặc đợi cho đến khi webhooks điền Billing_ Period_* trong Redis.

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