API de Suppression d’Arrière-plan RemBG – Documentation Développeur & Guide d’Intégration
Installation de 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") |
Configuration de votre environnement : Assurez-vous d'avoir un fichier .env dans la racine de votre projet contenant votre clé API.
Importation des modules nécessaires : Commencez par importer la fonction rembg de @remove-background-ai/rembg.js et le module dotenv pour gérer les variables d'environnement.
Configuration des callbacks de progression : La bibliothèque offre des callbacks onDownloadProgress et onUploadProgress pour suivre la progression des opérations de fichier. Dans l'exemple fourni, nous enregistrons ces événements directement dans la console.
Maintenant, regardons de plus près un exemple d'utilisation :
// 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();
});
N'oubliez pas, la fonction de nettoyage peut être appelée si vous souhaitez supprimer l'image traitée de votre disque après la suppression de l'arrière-plan.
Affichage de la barre de progression
Lors de l'intégration d'un service de suppression d'arrière-plan, il est souvent bénéfique de fournir aux utilisateurs un retour sur la progression de leur demande de téléchargement ou de téléversement. Pour faciliter cela, vous pouvez définir vos propres callbacks onDownloadProgress et onUploadProgress. Ces deux callbacks acceptent AxiosProgressEvent comme paramètre d'événement. Au fur et à mesure de la progression de la demande, ces callbacks sont invoqués plusieurs fois, vous permettant, par exemple, d'afficher une barre de progression et d'ajuster sa longueur en fonction de la progression.
(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)