Skip to content

Instantly share code, notes, and snippets.

@BackgroundCut
Created November 14, 2023 03:11
Show Gist options
  • Save BackgroundCut/f9baf2e264c57a07ed88c040e44ac242 to your computer and use it in GitHub Desktop.
Save BackgroundCut/f9baf2e264c57a07ed88c040e44ac242 to your computer and use it in GitHub Desktop.
import requests
from requests.exceptions import RequestException
# API configuration
API_ENDPOINT = "https://api.backgroundcut.co/v2/cut/"
API_KEY = 'YOUR-API-KEY'
IMAGE_PATH = "/path/to/image.jpg"
REQUEST_PARAMETERS = {
'quality': 'medium',
'return_format': 'webp',
'max_resolution': '12000000', # 12 MegaPixels (for example 4000 * 3000)
}
TIMEOUT_DURATION = 20 # seconds
LOCAL_OUTPUT_FILENAME = "/path/to/output.webp"
try:
# Open image file and send POST request to API endpoint
with open(IMAGE_PATH, 'rb') as image_file:
image_data = {'image_file': image_file}
response = requests.post(API_ENDPOINT,
files=image_data,
data=REQUEST_PARAMETERS,
headers={'Authorization': f'{API_KEY}'},
timeout=TIMEOUT_DURATION)
# Check response status code
if response.status_code == 200:
# The API returns the image directly in the response
with open(LOCAL_OUTPUT_FILENAME, 'wb') as f:
f.write(response.content)
elif 400 <= response.status_code < 500:
try:
error_message = response.json().get('error', 'No error message provided')
except:
error_message = 'No error message provided'
raise Exception(
f"Client error. Status Code: {response.status_code}. Error Message: {error_message}"
)
elif 500 <= response.status_code < 600:
raise Exception(f"Server error. Status Code: {response.status_code}")
else:
raise Exception(
f"Unexpected response. Status Code: {response.status_code}")
except RequestException as req_err:
# Other errors (e.g., network issues, timeouts, etc.)
raise Exception(f"Request error occurred: {req_err}")
except Exception as e:
# Fallback for other unforeseen errors
raise Exception(f"An error occurred: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment