Skip to content

Instantly share code, notes, and snippets.

@BackgroundCut
Created October 30, 2023 19:15
Show Gist options
  • Save BackgroundCut/b145b2ff5d256636b60f8a9b679169c8 to your computer and use it in GitHub Desktop.
Save BackgroundCut/b145b2ff5d256636b60f8a9b679169c8 to your computer and use it in GitHub Desktop.
<?php
// API configuration
$apiEndpoint = "https://backgroundcut.co/api/v1/cut/";
$apiKey = 'YOUR-API-KEY';
$requestParameters = [
'file_url' => 'https://www.example.com/example.jpg',
'max_resolution' => '12000000', // 12 MegaPixels (for example 4000 * 3000)
'quality' => 'medium',
'return_format' => 'webp',
];
$timeoutDuration = 20; // seconds
$localFilename = "/path/to/output.webp";
// Authorization header
$authHeader = ['Authorization' => "Token $apiKey"];
try {
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiEndpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestParameters));
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($key, $value) {
return "$key: $value";
}, array_keys($authHeader), $authHeader));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutDuration);
// Send the request and get the response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response === false) {
throw new Exception("Request error occurred: " . curl_error($ch));
}
// Check response status code
if ($httpCode == 200) {
$responseData = json_decode($response, true);
$outputImageUrl = $responseData['output_image_url'];
// Download the output image
$outputImageContent = file_get_contents($outputImageUrl);
if ($outputImageContent === false) {
throw new Exception("Failed to download the output image");
}
// Save the image
file_put_contents($localFilename, $outputImageContent);
} elseif ($httpCode >= 400 && $httpCode < 500) {
$error_message = json_decode($response, true)['error'] ?? 'No error message provided';
throw new Exception("Client error. Status Code: $httpCode. Error Message: $error_message");
} elseif ($httpCode >= 500 && $httpCode < 600) {
throw new Exception("Server error. Status Code: $httpCode");
} else {
throw new Exception("Unexpected response. Status Code: $httpCode");
}
} catch (Exception $e) {
// Fallback for other unforeseen errors
throw new Exception("An error occurred: " . $e->getMessage());
} finally {
if (isset($ch)) {
curl_close($ch);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment