Open In App

Create an Image Background Remover App Using React

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create an Image Background Remover App Using ReactJS. Image editing tools play a crucial role in various industries, from graphic design to e-commerce. One common task is removing backgrounds from images, a process that traditionally requires specialized software. we’ll walk through the process of building an image background remover app using React.

Preview of final output: Let us have a look at how the final output will look like.

r2

Prerequisites:

Approach to Create Image Background Remover App using React:

  • State: Manages image (original) and bgRemove (removed) with useState.
  • Upload: Input field for image selection, updating image state.
  • Background Removal: handleRemoveBackground on button click. Sends image to Remove.bg API. Updates bgRemove with resulting image URL.
  • Previews: Two divs for original and removed images. Uses URL.createObjectURL for image URLs.
  • Download Button: Appears if background removal is successful. Links to download the removed image.
  • Styling: Bootstrap classes for clean UI.
  • Structure: Well-organized components for clarity.

Steps to create the project:

Step 1: Creating a new React project using Create React App. Open your terminal and run the following command:

npx create-react-app project_name

Step 2: Navigate into the newly created project directory:

cd  project_name

Step 3: Install the necessory package using the following command:

npm install bootstrap

Step 4: Create an account on remove.bg. using the URL https://www.remove.bg/.

Step 5: sign up with your email, verify, log in, explore settings, retrieve API key if needed, upgrade if necessary, and start using for background removal.Then you will be direct go to My Account and select the Tools & API page, Choose the api url from there and copy it:

api2

Folder Structure:

removerList

The updated dependencies in package.json file will look like:

"dependencies": {
"bootstrap": "^5.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Modify the following code to create the app:

CSS




/* App.css */
 
/* Center content vertically and horizontally */
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: auto;
    padding: 20px;
    border: 1px solid #e4caca;
    border-radius: 10px;
    max-width: 300px;
    margin: 50px;
    background-color: #e3d5d5;
}
 
/* Title styles */
h1 {
    text-align: center;
    margin-bottom: 20px;
}
 
/* Style input file button */
.input-file {
    margin-bottom: 20px;
}
 
/* Style image previews */
.image-preview {
    border: 2px solid #cf8484;
    border-radius: 5px;
    margin-bottom: 20px;
    overflow: hidden;
}
 
.image-preview img {
    width: 100%;
    height: auto;
}
 
/* Style download button */
.btn-download {
    background-color: #28a745;
    color: #fff;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}
 
.btn-download:hover {
    background-color: #218838;
}
 
/* Style remove background button */
.btn-remove-bg {
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}
 
.btn-remove-bg:hover {
    background-color: #0056b3;
}


Javascript




// App.js
 
import React from 'react';
import RemoveBackground
    from './components/RemoveBackground';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
 
function App() {
    return (
        <div className="App">
            <RemoveBackground />
        </div>
    );
}
 
export default App;


Javascript




// RemoveBackground.js
 
import React, {
  useState
} from 'react';
 
export default function RemoveBackground() {
  const [image, setImage] = useState(null);
  const [bgRemove, setBgRemove] = useState(null);
 
  const handleRemoveBackground = async () => {
      const apiKey = "njv7RHG7MqkW3iqVX9wgPLxm";
      const apiUrl = "https://api.remove.bg/v1.0/removebg";
 
      const formData = new FormData();
      formData.append("image_file", image, image.name);
      formData.append("size", 'auto');
 
      try {
          const res = await fetch(apiUrl, {
              method: 'POST',
              headers: {
                  'X-Api-Key': apiKey
              },
              body: formData
          });
 
          const data = await res.blob();
          const imageUrl = URL.createObjectURL(data);
          setBgRemove(imageUrl);
      } catch (error) {
          console.log(error);
      }
  };
 
  return (
      <div className="container">
          <h1 className="mb-4">Image Background Remover</h1>
          <div className="input-file mb-4">
              <label htmlFor="userImg" className="info_text">
                  Select a File
              </label>
              <input
                  type="file"
                  id="userImg"
                  className="form-control-file"
                  onChange={(e) => setImage(e.target.files[0])}
                  required
              />
          </div>
          <div className="d-flex mb-4">
              {image && (
                  <div className="image-preview mr-2">
                      <img src={image ? URL.createObjectURL(image) : ""}
                          alt="" />
                  </div>
              )}
              {bgRemove && (
                  <div className="image-preview">
                      <img src={bgRemove} alt="" />
                  </div>
              )}
          </div>
          {bgRemove && (
              <div className="mb-4">
                  <a href={bgRemove}
                      download="background_removed_image.png">
                      <button className="btn btn-success">
                          Download
                      </button>
                  </a>
              </div>
          )}
          <div>
              <button type="button"
                  onClick={handleRemoveBackground}
                  className="btn btn-primary">
                  Remove Background
              </button>
          </div>
      </div>
  );
}


Start Your application using the following command.

npm start

Output: Open web-browser and type the following URL http://localhost:3000/

bandicam2024-03-0620-40-23-834-ezgifcom-video-to-gif-converter



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads