Welcome folks today in this blog post we will be removing background
of images using rembg
and formidable
library in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i formidable
And after that you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
const express = require('express'); const formidable = require('formidable'); const { exec } = require('child_process'); const fs = require('fs') const app = express(); const PORT = 3000; app.use(express.static('public')); app.get('/',(req,res) => { res.sendFile(__dirname + "/index.html") }) app.post('/remove-background', (req, res) => { const form = new formidable.IncomingForm(); form.parse(req, (err, fields, files) => { if (err) { console.error('Error parsing form:', err); return res.status(500).send('Internal Server Error'); } const inputFile = files.image; console.log(inputFile) let outputPath = Date.now() + ".jpg" // Execute the Rembg command to remove background const command = `rembg i ${inputFile.filepath} ${outputPath}`; exec(command, (error, stdout, stderr) => { if (error) { console.error('Error running Rembg:', error); return res.status(500).send('Internal Server Error'); } res.download(outputPath,() => { fs.unlinkSync(outputPath) }) }); }); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); |
As you can see we are importing the express
and formidable
library at the top and then we are executing the rembg
command to remove the background of the image
which is selected by the user using the formidable
library. And then we are downloading the output
image as an attachment.
And now we need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <head> <title>Remove Background</title> </head> <body> <h1>Remove Background</h1> <form id="upload-form" action="/remove-background" method="POST" enctype="multipart/form-data" > <input type="file" name="image" accept="image/*" /> <button type="submit">Remove Background</button> </form> </body> </html> |
As you can see we are showing a simple html5
form where user can select the image
and then we have the button to remove the background.