From ad7d94c8d054c79da7c35a7495e9d24b1f8f86dd Mon Sep 17 00:00:00 2001 From: theoleuthardt Date: Sat, 22 Feb 2025 14:30:52 +0100 Subject: [PATCH] feat: frontend page with remove bg api call and automatic download of output image --- frontend/src/app/bg-remover/layout.tsx | 20 ++++++ frontend/src/app/bg-remover/page.tsx | 96 ++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 frontend/src/app/bg-remover/layout.tsx create mode 100644 frontend/src/app/bg-remover/page.tsx diff --git a/frontend/src/app/bg-remover/layout.tsx b/frontend/src/app/bg-remover/layout.tsx new file mode 100644 index 0000000..4f2608a --- /dev/null +++ b/frontend/src/app/bg-remover/layout.tsx @@ -0,0 +1,20 @@ +import React from "react"; +import type { Metadata } from "next"; +import { toolLinks } from "@/constants"; + +export const metadata: Metadata = { + title: toolLinks[6].title, + description: "Remove backgrounds from your images!", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + {children} + + ); +} diff --git a/frontend/src/app/bg-remover/page.tsx b/frontend/src/app/bg-remover/page.tsx new file mode 100644 index 0000000..7ddf051 --- /dev/null +++ b/frontend/src/app/bg-remover/page.tsx @@ -0,0 +1,96 @@ +"use client"; +import React, { useState } from "react"; +import Navbar from "../../components/Navbar"; +import Footer from "../../components/Footer"; +import Button from "../../components/Button"; + +export default function BGRemover() { + const [file, setFile] = useState(null); + const [loading, setLoading] = useState(false); + + const handleFileChange = (event: React.ChangeEvent) => { + event.preventDefault(); + + if (event.target.files && event.target.files.length > 0) { + const selectedFile = event.target.files[0]; + setFile(selectedFile); + } + }; + + const removeBG = async () => { + if (!file) { + alert("No file selected"); + return; + } else if (file.size > 5 * 1024 * 1024) { + alert("File size should be less than 5MB"); + return; + } + + const formData = new FormData(); + formData.append("file", file); + + setLoading(true); + + try { + const response = await fetch(process.env.backend_url + "/api/remove-bg", { + method: "POST", + body: formData, + }); + + if (!response.ok) { + console.error(`Error: ${response.statusText}`); + return; + } + + const blob = await response.blob(); + const url = window.URL.createObjectURL(blob); + const filename = file.name.split(".")[0]; + + const a = document.createElement("a"); + a.href = url; + a.download = `${filename}.png`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + + setTimeout(() => { + URL.revokeObjectURL(url); + }, 5000); + } catch (error) { + console.error("Error while converting:", error); + alert("Error while converting!"); + } finally { + setLoading(false); + } + }; + + return ( +
+ +
+

bg-remover

+
+ +
+
+
+
+
+ ); +}