-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
81 lines (67 loc) · 2.65 KB
/
script.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
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
81
const imageUpload = document.getElementById('imageUpload');
const removeBackgroundBtn = document.getElementById("removeBackgroundBtn");
const loader = document.getElementById('loader');
const outputCanvas = document.getElementById('outputCanvas')
const downloadBtn = document.getElementById('downloadBtn');
const API_KEY = 'API Key Goes Here';
//50 credits per month
function enableDownload() {
downloadBtn.removeAttribute('disabled');
}
function disableDownload() {
downloadBtn.setAttribute('disabled', '');
}
imageUpload.addEventListener('change', () => {
if (imageUpload.files.length > 0) {
removeBackgroundBtn.removeAttribute('disabled');
} else {
removeBackgroundBtn.setAttribute('disabled')
}
})
removeBackgroundBtn.addEventListener('click', () => {
const file = imageUpload.files[0];
const formData = new FormData();
formData.append('image_file', file);
loader.style.display = 'block';
removeBackgroundBtn.setAttribute('disabled', '');
disableDownload();
fetch('https://api.remove.bg/v1.0/removebg', {
method: 'POST',
headers: {
'X-Api-Key': API_KEY
},
body: formData
})
.then(response => response.blob())
.then(blob => {
const imageUrl = URL.createObjectURL(blob);
const image = new Image();
image.src = imageUrl;
image.onload = () => {
const { width, height } = image;
outputCanvas.width = width;
outputCanvas.height = height;
const ctx = outputCanvas.getContext('2d');
ctx.drawImage(image, 0, 0);
URL.revokeObjectURL(imageUrl);
loader.style.display = 'none';
outputCanvas.style.display = 'block';
enableDownload();
};
})
.catch(error => {
console.error(error);
disableDownload();
alert('An Issue Has been occured try after some time')
loader.style.display = 'none';
})
downloadBtn.addEventListener('click', () => {
const canvas = document.getElementById('outputCanvas');
const imageType = 'image/png'; // Modify this if you want a different image format
const imageData = canvas.toDataURL(imageType);
const downloadLink = document.createElement('a');
downloadLink.href = imageData;
downloadLink.download = 'modified_image.png'; // Modify the filename and extension as needed
downloadLink.click();
});
})