// White background JPEGconst result = await poof.removeBackground(image, { format: 'jpg', channels: 'rgb', bgColor: '#ffffff',});// Small cropped thumbnailconst result = await poof.removeBackground(image, { size: 'preview', crop: true,});// Crop to a 1:1 aspect ratio around the subjectconst result = await poof.removeBackground(image, { crop: '1:1' });// Grayscale alpha mask onlyconst result = await poof.removeBackground(image, { channels: 'alpha' });// Consistent product shots: crop, then pad 10% horizontally and 7.5% verticallyconst result = await poof.removeBackground(image, { crop: true, padding: '10%,7.5%',});// Exact 500x500 output, never stretched: subject cropped, padded, centredconst result = await poof.removeBackground(image, { crop: true, width: 500, height: 500 });// Fill a 1080x1080 canvas on white instead (overflow cropped around the subject)const result = await poof.removeBackground(image, { width: 1080, height: 1080, fit: 'cover', format: 'jpg', bgColor: '#ffffff',});// Cap the width at 1000px, keep the aspect ratio, leave smaller images aloneconst result = await poof.removeBackground(image, { width: 1000, fit: 'scale-down' });// WebP for webconst result = await poof.removeBackground(image, { format: 'webp', size: 'medium',});
Option
Values
format
'png' (default), 'jpg', 'webp'
channels
'rgba' (default), 'rgb', 'alpha'
bgColor
Hex, rgb(), or CSS color name. Setting it fills the background, so the result is opaque; with channels: 'rgb' and no bgColor the background is white. Ignored with channels: 'alpha'
size
'full' (default), 'preview', 'medium', 'hd'
crop
true, false, or an aspect ratio string like '1:1'
padding
Padding around the subject when crop is set: '10%' or '0.1' for both axes, or '10%,7.5%' for horizontal,vertical (default 10%)
channels: 'alpha', padding, aspect-ratio crop, the matte metadata fields and the width / height / fit output-size options need @poof-bg/js 1.1.0 or later; video needs 1.2.0 or later.
Every successful image call costs 1 credit regardless of options. Failed calls are not billed. Video costs 5 credits per started second of source video (10 above 30 fps), charged when the job is accepted and refunded if it fails. Animated GIF input is billed at 5 credits per second whatever its frame rate. See Video.
Result and Metadata
removeBackground() resolves to a RemoveBackgroundResult:
const result = await poof.removeBackground(image);result.data; // ArrayBuffer - the processed imageresult.metadata.requestId; // string - unique request IDresult.metadata.processingTimeMs; // number - processing timeresult.metadata.width; // number - output widthresult.metadata.height; // number - output heightresult.metadata.contentType; // string - e.g. "image/png"result.metadata.matteConfidence; // number | undefined - 0-1, how decisive the mask isresult.metadata.matteAmbiguousRatio; // number | undefined - 0-1, fraction of uncertain pixels// Node.js: write to diskawait fs.writeFile('result.png', Buffer.from(result.data));// Browser: display itconst url = URL.createObjectURL(new Blob([result.data], { type: result.metadata.contentType }));
Flagging Results for Review
matteConfidence (0–1) is how decisive the alpha mask is; matteAmbiguousRatio (0–1) is the fraction of pixels with alpha between 0.1 and 0.9. Both are heuristics, not calibrated probabilities. The dashboard playground flags a result for review when the ambiguous ratio is above 0.15:
const result = await poof.removeBackground(image);await fs.writeFile('result.png', Buffer.from(result.data));const { matteAmbiguousRatio, requestId } = result.metadata;if (matteAmbiguousRatio !== undefined && matteAmbiguousRatio > 0.15) { console.warn(`Review ${requestId}: ${(matteAmbiguousRatio * 100).toFixed(0)}% of pixels are uncertain`);}
Parallel Processing
import { Poof } from '@poof-bg/js';import fs from 'fs/promises';const poof = new Poof({ apiKey: process.env.POOF_API_KEY! });async function processImages(imagePaths: string[]) { return Promise.all( imagePaths.map(async (imagePath) => { const result = await poof.removeBackground(imagePath); const outputPath = imagePath.replace(/\.[^.]+$/, '_no_bg.png'); await fs.writeFile(outputPath, Buffer.from(result.data)); return outputPath; }) );}// Keep concurrency at or below your plan's per-minute limit (see Rate Limit Exceeded)await processImages(['photo1.jpg', 'photo2.jpg', 'photo3.jpg']);
Account Info
me() returns the /me response. It is free and not rate limited.
const account = await poof.me();console.log(`Plan: ${account.plan}`);console.log(`Credits used: ${account.usedCredits}/${account.maxCredits}`);console.log(`Remaining: ${account.maxCredits - account.usedCredits}`);// Present only when Auto Recharge is on (fraction of the plan limit, e.g. 0.9)account.autoRechargeThreshold;
Error Handling
All errors extend PoofError, which exposes .code, .status, .requestId, .details and .message. Subclasses are chosen by the API error code:
// app/api/remove-bg/route.tsimport { Poof } from '@poof-bg/js';import { NextRequest, NextResponse } from 'next/server';const poof = new Poof({ apiKey: process.env.POOF_API_KEY! });export async function POST(request: NextRequest) { const formData = await request.formData(); const file = formData.get('image') as File | null; if (!file) { return NextResponse.json({ error: 'No image' }, { status: 400 }); } const result = await poof.removeBackground(file); return new NextResponse(result.data, { headers: { 'Content-Type': result.metadata.contentType }, });}
Video
removeBackground() accepts video too (@poof-bg/js 1.2.0 or later). Poof detects the media type from the bytes: an image resolves to a RemoveBackgroundResult as above, a video is accepted as an asynchronous job and the call resolves to a Job instead. Use the isJob() type guard to tell them apart, wait for the job, then download its resultUrl.
import { Poof, isJob } from '@poof-bg/js';import fs from 'fs/promises';const poof = new Poof({ apiKey: 'pk_your_api_key' });const result = await poof.removeBackground('clip.mp4', { format: 'webm', channels: 'rgba' });if (!isJob(result)) throw new Error('expected a video job');console.log(result.id, result.status, result.credits); // job_8f3a1c2e9b7d4a10 queued 65const job = await poof.waitForJob(result, { onProgress: (j) => console.log(`${Math.round(j.progress * 100)}%`),});const video = await fetch(job.resultUrl!);await fs.writeFile('clip-no-bg.webm', Buffer.from(await video.arrayBuffer()));
An animated GIF works as input too, and format: 'gif' returns a looping transparent GIF (1-bit transparency, no audio, capped at 1280 px on the longest side, 720p for widescreen, and 50 fps) for stickers and chat.Pass wait: true to resolve with the finished job in one call:
In the browser, pass the File from an <input type="file"> exactly as for images; the result URL can be set straight on a <video> element.
Video options
Option
Values
format
'webm' (default, VP9 with alpha), 'mov' (ProRes 4444), 'mp4' (H.264, composited on bgColor), 'gif' (looping GIF, 1-bit transparency, no audio, capped at 1280 px on the longest side, 720p for widescreen, and 50 fps)
channels
'rgba' (default), 'rgb', 'alpha' (grayscale matte, no audio)
bgColor
Background colour. Setting it fills the background, so the result is opaque in every format (WebM, MOV and GIF included); without it rgb and mp4 are on white. Ignored with channels: 'alpha'
size
Caps the longest side: 'full' (default) the source resolution up to 4096 px (4K), 'hd' 1920 px (1080p), 'medium' 1280 px, 'preview' 640 px
wait
true to poll until the job finishes before resolving
crop, padding, width, height and fit are image-only; sending one with a video rejects with a PoofError of code validation_error.
Job fields
Field
Type
Description
id
string
Job id (job_…)
status
'queued' | 'processing' | 'completed' | 'failed'
Current state
progress
number
0 to 1
durationSeconds, fps, width, height, frames
number
Source clip properties
credits
number
Credits charged (refunded if the job fails)
format, channels
string
Requested output
resultUrl
string | null
Direct CDN link to the result once completed; valid for 24 hours
expiresAt
string | null
When resultUrl stops working
error
{ code, message } | null
Set when the job failed
waitForJob(jobOrId, { pollIntervalMs = 3000, timeoutMs = 600000, onProgress }) polls GET /jobs/{id} (free, not rate limited) and rejects with a PoofError of code job_failed if the job fails, or timeout after timeoutMs. The full job lifecycle is described in the Jobs reference.