/**
* Remove background
* @async
* @function removeBackground
* @param {string} url - The URL of the image to remove the background from.
* @returns {Promise} - The URL of the processed image with the background removed.
* @throws {Error} - If an error occurs while downloading, uploading, or processing the image.
*
* @example
* removeBackground("https://example.com/image.jpg")
* .then(resultUrl => console.log(resultUrl))
* .catch(error => console.error("Error:", error.message));
*/
async function removeBackground(url) {
try {
const images = await fetch(url);
if (!images.ok) {
throw new Error("Failed download image.");
}
const imageBuffer = await images.arrayBuffer();
const contentType = images.headers.get("content-type");
const upload = await fetch(
"https://aibackgroundremover.org/api/get-upload-url",
{
headers: {
accept: "*/*",
referer: "https://aibackgroundremover.org/",
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0",
},
},
);
const { uploadUrl, publicUrl } = await upload.json();
const upres = await fetch(uploadUrl, {
method: "PUT",
body: imageBuffer,
headers: {
"Content-Type": contentType,
},
});
if (!upres.ok) {
throw new Error("Failed upload.");
}
const removebg = await fetch(
"https://aibackgroundremover.org/api/remove-bg",
{
method: "POST",
headers: {
accept: "*/*",
"content-type": "application/json",
referer: "https://aibackgroundremover.org/",
},
body: JSON.stringify({ image: publicUrl }),
},
);
const { id } = await removebg.json();
let status_response;
do {
await new Promise((resolve) => setTimeout(resolve, 2000));
const statusCheck = await fetch(
`https://aibackgroundremover.org/api/check-status?id=${id}`,
{
headers: {
accept: "*/*",
referer: "https://aibackgroundremover.org/",
},
},
);
status_response = await statusCheck.json();
} while (
status_response.status === "starting" ||
status_response.status === "processing"
);
if (status_response.status === "succeeded") {
return status_response.output;
}
throw new Error(status_response.error || "Error Processing.");
} catch (error) {
console.error("Error:", error.message);
throw error;
}
}
// Example usage
removeBackground(
"https://tmpfiles.org/dl/20842097/KirisakiChitoge.jpg",
)
.then((resultUrl) => console.log(resultUrl))
.catch((error) => console.error("Error:", error.message));