const axios = require('axios'); const fs = require('fs'); const path = require('path'); const FormData = require('form-data'); class ILoveImgRemoveBG { BASE_URL = 'https://www.iloveimg.com'; constructor() { this.token = null; this.taskId = null; this.workerServer = null; this.apiVersion = 'v1'; } async getInitialConfig() { console.log('[*] Fetching initial config...'); const resp = await axios.get( 'https://www.iloveimg.com/remove-background', { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' } } ); const html = resp.data; const tokenMatch = html.match(/"token":"([^"]+)"/); if (tokenMatch) { this.token = tokenMatch[1]; console.log( `[+] Token found: ${this.token.substring(0, 50)}...` ); } const taskMatch = html.match( /ilovepdfConfig\.taskId\s*=\s*'([^']+)'/ ); if (taskMatch) { this.taskId = taskMatch[1]; console.log( `[+] Task ID found: ${this.taskId.substring(0, 30)}...` ); } const serversMatch = html.match(/"servers":\s*\[([^\]]+)\]/); if (serversMatch) { const servers = JSON.parse('[' + serversMatch[1] + ']'); this.workerServer = `https://${servers[0]}.iloveimg.com`; console.log(`[+] Worker server: ${this.workerServer}`); } if (!this.token || !this.taskId || !this.workerServer) { throw new Error('Failed to extract config from page'); } return true; } async uploadFile(filePath) { console.log(`[*] Uploading ${filePath}...`); const form = new FormData(); form.append('task', this.taskId); form.append('v', '2.5.0'); form.append('preview', '1'); form.append( 'file', fs.createReadStream(filePath), path.basename(filePath) ); const resp = await axios.post( `${this.workerServer}/${this.apiVersion}/upload`, form, { headers: { Authorization: `Bearer ${this.token}`, ...form.getHeaders() }, maxBodyLength: Infinity, validateStatus: () => true } ); if (resp.status !== 200) { throw new Error( `Upload failed: ${resp.status} - ${JSON.stringify(resp.data)}` ); } console.log( `[+] Upload success: ${JSON.stringify(resp.data).substring( 0, 100 )}` ); return resp.data.server_filename; } async removeBackground(serverFilename) { console.log('[*] Removing background...'); const form = new FormData(); form.append('task', this.taskId); form.append('server_filename', serverFilename); const resp = await axios.post( `${this.workerServer}/${this.apiVersion}/removebackground`, form, { headers: { Authorization: `Bearer ${this.token}`, ...form.getHeaders() }, responseType: 'arraybuffer', validateStatus: () => true } ); if (resp.status !== 200) { throw new Error(`Remove background failed: ${resp.status}`); } const buffer = Buffer.from(resp.data); console.log('[+] Remove background success'); return buffer; } async process(inputFile, outputFile = null) { if (!outputFile) { const ext = path.extname(inputFile); const base = path.basename(inputFile, ext); outputFile = `${base}_nobg.png`; } await this.getInitialConfig(); const serverFilename = await this.uploadFile(inputFile); console.log(`[+] Server filename: ${serverFilename}`); const result = await this.removeBackground(serverFilename); fs.writeFileSync(outputFile, result); console.log(`[+] Result saved to: ${outputFile}`); return outputFile; } } async function main() { const args = process.argv.slice(2); if (args.length < 1) { console.log( `Usage: node ${path.basename(__filename)} [output_file]` ); console.log(''); console.log('Examples:'); console.log(`node ${path.basename(__filename)} photo.jpg`); console.log( `node ${path.basename(__filename)} photo.jpg result.png` ); process.exit(1); } const inputFile = args[0]; const outputFile = args[1] || null; if (!fs.existsSync(inputFile)) { console.error(`Error: File not found: ${inputFile}`); process.exit(1); } const scraper = new ILoveImgRemoveBG(); try { const result = await scraper.process( inputFile, outputFile ); console.log(`\n[SUCCESS] Output saved to: ${result}`); } catch (err) { console.error('\n[ERROR]', err.message); if (err.response) { console.error('Status:', err.response.status); console.error('Response:', err.response.data); } process.exit(1); } } main();