Simply copy and paste the code into your project, and update the placeholder with your own API key.
consthttps=require('https');constfs=require('fs');// Please replace with your own apiKeyconstapiKey='YOUR_API_KEY_HERE';functionremoveBackground(imagePath, savePath) {returnnewPromise((resolve, reject) => {constboundary='--------------------------'+Date.now().toString(16);constpostOptions= { hostname:'sdk.photoroom.com', path:'/v1/segment', method:'POST', headers: {'Content-Type':`multipart/form-data; boundary=${boundary}`,'X-API-Key': apiKey } };constreq=https.request(postOptions, (res) => {// Check if the response is an imageconstisImage= ['image/jpeg','image/png','image/gif'].includes(res.headers['content-type']);if (!isImage) {let errorData ='';res.on('data', (chunk) => errorData += chunk);res.on('end', () =>reject(newError(`Expected an image response, but received: ${errorData}`)));return; }// Create a write stream to save the imageconstfileStream=fs.createWriteStream(savePath);res.pipe(fileStream);fileStream.on('finish', () => {resolve(`Image saved to ${savePath}`); });fileStream.on('error', (error) => {reject(newError(`Failed to save the image: ${error.message}`)); }); });req.on('error', (error) => {reject(error); });// Write form datareq.write(`--${boundary}\r\n`);req.write(`Content-Disposition: form-data; name="image_file"; filename="${imagePath.split('/').pop()}"\r\n`);req.write('Content-Type: image/jpeg\r\n\r\n'); // assuming JPEG, adjust if another format is usedconstuploadStream=fs.createReadStream(imagePath);uploadStream.on('end', () => {req.write('\r\n');req.write(`--${boundary}--\r\n`);req.end(); });uploadStream.pipe(req, { end:false }); });}module.exports= removeBackground;
Step 3: Call the API
Now it's time to call the API in your code! Just use the function removeBackground() and pass as arguments both the path of the original image and the path where the result image should be saved.
That's it! With just these three easy steps, you can integrate the PhotoRoom Background Removal API into your Node.js project and provide your users with high-quality images with clean backgrounds.
According to resellers who use the PhotoRoom app, this feature can increase sales by 20 up to 100%.