-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathscript.js
More file actions
80 lines (66 loc) · 2.12 KB
/
script.js
File metadata and controls
80 lines (66 loc) · 2.12 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
let imageURL;
const fileInput = document.getElementById("fileInput");
const file = document.getElementById("file");
const uploadedImage = document.getElementById("uploadedImage");
const removeBgButton = document.getElementById("removeBgButton");
const downloadButton = document.getElementById("downloadBtn");
const reloadButton = document.getElementById("reloadBtn");
// Hide the download button initially
reloadButton.style.display = "none";
downloadButton.style.display = "none";
fileInput.addEventListener("change", function (event) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = function (e) {
uploadedImage.src = e.target.result;
};
reader.readAsDataURL(event.target.files[0]);
}
});
function submitHandler() {
removeBgButton.classList.toggle("btn_loading");
const fileInput = document.getElementById("fileInput");
console.log(fileInput.files);
const image = fileInput.files[0];
if (!fileInput.files || fileInput.files.length === 0) {
alert("Please select an image before submitting.");
return;
}
// Multipart file
const formData = new FormData();
formData.append("image_file", image);
formData.append("size", "auto");
const apiKey = "5V4yNGbdJ9Dr83u6GAbxD8Vw";
fetch("https://api.remove.bg/v1.0/removebg", {
method: "POST",
headers: {
"X-Api-Key": apiKey,
},
body: formData,
})
.then(function (response) {
return response.blob();
})
.then(function (blob) {
console.log(blob);
const url = URL.createObjectURL(blob);
imageURL = url;
uploadedImage.src = url;
reloadButton.style.display = "block";
file.style.display = "none";
downloadButton.style.display = "block";
removeBgButton.style.display = "none";
})
.catch();
}
function downloadFile() {
var anchorElement = document.createElement("a");
anchorElement.href = imageURL;
anchorElement.download = "removed_bg.png";
document.body.appendChild(anchorElement);
anchorElement.click();
document.body.removeChild(anchorElement);
}
function reset() {
window.location.reload();
}