Remove Background - Penghapus Latar Belakang.
No comments yet. Be the first to comment!
1const axios = require('axios');
2const fs = require('fs');
3const path = require('path');
4const FormData = require('form-data');
5
6class ILoveImgRemoveBG {
7 BASE_URL = 'https://www.iloveimg.com';
8
9 constructor() {
10 this.token = null;
11 this.taskId = null;
12 this.workerServer = null;
13 this.apiVersion = 'v1';
14 }
15
16 async getInitialConfig() {
17 console.log('[*] Fetching initial config...');
18
19 const resp = await axios.get(
20 'https://www.iloveimg.com/remove-background',
21 {
22 headers: {
23 'User-Agent':
24 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
25 Accept:
26 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
27 }
28 }
29 );
30
31 const html = resp.data;
32
33 const tokenMatch = html.match(/"token":"([^"]+)"/);
34
35 if (tokenMatch) {
36 this.token = tokenMatch[1];
37 console.log(
38 `[+] Token found: ${this.token.substring(0, 50)}...`
39 );
40 }
41
42 const taskMatch = html.match(
43 /ilovepdfConfig\.taskId\s*=\s*'([^']+)'/
44 );
45
46 if (taskMatch) {
47 this.taskId = taskMatch[1];
48 console.log(
49 `[+] Task ID found: ${this.taskId.substring(0, 30)}...`
50 );
51 }
52
53 const serversMatch = html.match(/"servers":\s*\[([^\]]+)\]/);
54
55 if (serversMatch) {
56 const servers = JSON.parse('[' + serversMatch[1] + ']');
57 this.workerServer = `https://${servers[0]}.iloveimg.com`;
58
59 console.log(`[+] Worker server: ${this.workerServer}`);
60 }
61
62 if (!this.token || !this.taskId || !this.workerServer) {
63 throw new Error('Failed to extract config from page');
64 }
65
66 return true;
67 }
68
69 async uploadFile(filePath) {
70 console.log(`[*] Uploading ${filePath}...`);
71
72 const form = new FormData();
73
74 form.append('task', this.taskId);
75 form.append('v', '2.5.0');
76 form.append('preview', '1');
77
78 form.append(
79 'file',
80 fs.createReadStream(filePath),
81 path.basename(filePath)
82 );
83
84 const resp = await axios.post(
85 `${this.workerServer}/${this.apiVersion}/upload`,
86 form,
87 {
88 headers: {
89 Authorization: `Bearer ${this.token}`,
90 ...form.getHeaders()
91 },
92 maxBodyLength: Infinity,
93 validateStatus: () => true
94 }
95 );
96
97 if (resp.status !== 200) {
98 throw new Error(
99 `Upload failed: ${resp.status} - ${JSON.stringify(resp.data)}`
100 );
101 }
102
103 console.log(
104 `[+] Upload success: ${JSON.stringify(resp.data).substring(
105 0,
106 100
107 )}`
108 );
109
110 return resp.data.server_filename;
111 }
112
113 async removeBackground(serverFilename) {
114 console.log('[*] Removing background...');
115
116 const form = new FormData();
117
118 form.append('task', this.taskId);
119 form.append('server_filename', serverFilename);
120
121 const resp = await axios.post(
122 `${this.workerServer}/${this.apiVersion}/removebackground`,
123 form,
124 {
125 headers: {
126 Authorization: `Bearer ${this.token}`,
127 ...form.getHeaders()
128 },
129 responseType: 'arraybuffer',
130 validateStatus: () => true
131 }
132 );
133
134 if (resp.status !== 200) {
135 throw new Error(`Remove background failed: ${resp.status}`);
136 }
137
138 const buffer = Buffer.from(resp.data);
139
140 console.log('[+] Remove background success');
141
142 return buffer;
143 }
144
145 async process(inputFile, outputFile = null) {
146 if (!outputFile) {
147 const ext = path.extname(inputFile);
148 const base = path.basename(inputFile, ext);
149 outputFile = `${base}_nobg.png`;
150 }
151
152 await this.getInitialConfig();
153
154 const serverFilename = await this.uploadFile(inputFile);
155
156 console.log(`[+] Server filename: ${serverFilename}`);
157
158 const result = await this.removeBackground(serverFilename);
159
160 fs.writeFileSync(outputFile, result);
161
162 console.log(`[+] Result saved to: ${outputFile}`);
163
164 return outputFile;
165 }
166}
167
168async function main() {
169 const args = process.argv.slice(2);
170
171 if (args.length < 1) {
172 console.log(
173 `Usage: node ${path.basename(__filename)} <image_file> [output_file]`
174 );
175
176 console.log('');
177 console.log('Examples:');
178 console.log(`node ${path.basename(__filename)} photo.jpg`);
179 console.log(
180 `node ${path.basename(__filename)} photo.jpg result.png`
181 );
182
183 process.exit(1);
184 }
185
186 const inputFile = args[0];
187 const outputFile = args[1] || null;
188
189 if (!fs.existsSync(inputFile)) {
190 console.error(`Error: File not found: ${inputFile}`);
191 process.exit(1);
192 }
193
194 const scraper = new ILoveImgRemoveBG();
195
196 try {
197 const result = await scraper.process(
198 inputFile,
199 outputFile
200 );
201
202 console.log(`\n[SUCCESS] Output saved to: ${result}`);
203 } catch (err) {
204 console.error('\n[ERROR]', err.message);
205
206 if (err.response) {
207 console.error('Status:', err.response.status);
208 console.error('Response:', err.response.data);
209 }
210
211 process.exit(1);
212 }
213}
214
215main();