Created
October 30, 2023 19:21
-
-
Save BackgroundCut/c2c47d14820b055840698a5e59036489 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios'); | |
const fs = require('fs'); | |
// API configuration | |
const API_ENDPOINT = "https://backgroundcut.co/api/v1/cut/"; | |
const API_KEY = 'YOUR-API-KEY'; | |
const REQUEST_PARAMETERS = { | |
'file_url': 'https://www.example.com/example.jpg', | |
'max_resolution': '12000000', // 12 MegaPixels (for example 4000 * 3000) | |
'quality': 'medium', | |
'return_format': 'webp', | |
}; | |
const TIMEOUT_DURATION = 20000; // milliseconds | |
const LOCAL_FILENAME = "/path/to/output.webp"; | |
// Authorization header | |
const authHeader = { 'Authorization': `Token ${API_KEY}` }; | |
axios.post(API_ENDPOINT, REQUEST_PARAMETERS, { | |
headers: authHeader, | |
timeout: TIMEOUT_DURATION | |
}) | |
.then(response => { | |
if (response.status === 200) { | |
const outputImageURL = response.data.output_image_url; | |
axios({ | |
method: 'get', | |
url: outputImageURL, | |
responseType: 'stream', | |
timeout: TIMEOUT_DURATION | |
}) | |
.then(imageResponse => { | |
const writer = fs.createWriteStream(LOCAL_FILENAME); | |
imageResponse.data.pipe(writer); | |
return new Promise((resolve, reject) => { | |
writer.on('finish', resolve); | |
writer.on('error', reject); | |
}); | |
}) | |
.catch(error => { | |
throw new Error(`Error while downloading and saving the image: ${error.message}`); | |
}); | |
} else if (response.status >= 400 && response.status < 500) { | |
const errorMessage = response.data.error || 'No error message provided'; | |
throw new Error(`Client error. Status Code: ${response.status}. Error Message: ${errorMessage}`); | |
} else if (response.status >= 500 && response.status < 600) { | |
throw new Error(`Server error. Status Code: ${response.status}`); | |
} else { | |
throw new Error(`Unexpected response. Status Code: ${response.status}`); | |
} | |
}) | |
.catch(error => { | |
if (axios.isAxiosError(error)) { | |
// Handle errors thrown by axios | |
throw new Error(`Request error occurred: ${error.message}`); | |
} else { | |
// Handle other errors | |
throw new Error(`An error occurred: ${error.message}`); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment