Skip to content

Instantly share code, notes, and snippets.

@BackgroundCut
Last active October 30, 2023 14:02
Show Gist options
  • Save BackgroundCut/271bada3e35ef8a4caf1786c34c5cd99 to your computer and use it in GitHub Desktop.
Save BackgroundCut/271bada3e35ef8a4caf1786c34c5cd99 to your computer and use it in GitHub Desktop.
import requests
from requests.exceptions import RequestException
# API configuration
API_ENDPOINT = "https://backgroundcut.co/api/v1/cut/"
API_KEY = 'YOUR-API-KEY'
IMAGE_PATH = "/path/to/image.jpg"
REQUEST_PARAMETERS = {
'max_resolution': '12000000', # 12 MegaPixels (for example 4000 * 3000)
'quality': 'medium',
'return_format': 'webp',
}
TIMEOUT_DURATION = 20 # seconds
LOCAL_FILENAME = "/path/to/output.webp"
# Authorization header
auth_header = {'Authorization': f'Token {API_KEY}'}
try:
# Open image file and send POST request to API endpoint
with open(IMAGE_PATH, 'rb') as image_file:
image_data = {'file': image_file}
response = requests.post(API_ENDPOINT,
files=image_data,
data=REQUEST_PARAMETERS,
headers=auth_header,
timeout=TIMEOUT_DURATION)
# Check response status code
if response.status_code == 200:
response_data = response.json()
output_image_url = response_data['output_image_url']
# Download the output image
output_image_response = requests.get(output_image_url, stream=True)
output_image_response.raise_for_status()
# Save the image
with open(LOCAL_FILENAME, 'wb') as f:
for chunk in output_image_response.iter_content(chunk_size=8192):
f.write(chunk)
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