Skip to content

Instantly share code, notes, and snippets.

@BackgroundCut
Created November 14, 2023 04:11
Show Gist options
  • Save BackgroundCut/7045a4afcd7dd64d29e1c86178964e5b to your computer and use it in GitHub Desktop.
Save BackgroundCut/7045a4afcd7dd64d29e1c86178964e5b to your computer and use it in GitHub Desktop.
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
// API configuration
const API_ENDPOINT = "https://api.backgroundcut.co/v2/cut/";
const API_KEY = 'YOUR-API-KEY';
const IMAGE_PATH = "/path/to/image.jpg";
const LOCAL_OUTPUT_FILENAME = "/path/to/output.webp";
const REQUEST_PARAMETERS = {
quality: 'medium',
return_format: 'webp',
max_resolution: '12000000', // 12 MegaPixels (for example 4000 * 3000)
};
const TIMEOUT_DURATION = 20000; // milliseconds
// Create a form data instance
const form = new FormData();
form.append('image_file', fs.createReadStream(IMAGE_PATH));
Object.keys(REQUEST_PARAMETERS).forEach(key => {
form.append(key, REQUEST_PARAMETERS[key]);
});
axios.post(API_ENDPOINT, form, {
headers: {
...form.getHeaders(),
'Authorization': API_KEY
},
responseType: 'arraybuffer', // To handle binary data (image)
timeout: TIMEOUT_DURATION
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
// Write the output image
fs.writeFileSync(LOCAL_OUTPUT_FILENAME, response.data);
} else {
throw new Error(`Unexpected response status: ${response.status}`);
}
})
.catch(error => {
if (error.response) {
// The server responded with a status code outside the 2xx range
let errorMessage = 'No error message provided';
try {
const errorData = JSON.parse(error.response.data.toString());
errorMessage = errorData.error || errorMessage;
} catch (parseError) {
// Error while parsing error response
}
console.error(`Error: ${errorMessage}`);
} else if (error.request) {
// The request was made but no response was received
console.error('No response received');
} else {
// Something happened in setting up the request
console.error('Error', error.message);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment