Created
October 30, 2023 14:33
-
-
Save BackgroundCut/c5b41aef6e1f6d843f9768dfd81848ce 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
<?php | |
// API configuration | |
$apiEndpoint = "https://backgroundcut.co/api/v1/cut/"; | |
$apiKey = 'YOUR-API-KEY'; | |
$imagePath = "/path/to/image.jpg"; | |
$requestParameters = [ | |
'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 { | |
// Initialize cURL session | |
$ch = curl_init(); | |
// Set cURL options | |
curl_setopt($ch, CURLOPT_URL, $apiEndpoint); | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $authHeader); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestParameters + ['file' => new CURLFile($imagePath)]); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutDuration); | |
// Execute cURL session and get response | |
$response = curl_exec($ch); | |
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
curl_close($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 image from: $outputImageUrl"); | |
} | |
// Save the image | |
file_put_contents($localFilename, $outputImageContent); | |
} elseif ($httpCode >= 400 && $httpCode < 500) { | |
$errorMessage = json_decode($response, true)['error'] ?? 'No error message provided'; | |
throw new Exception("Client error. Status Code: $httpCode. Error Message: $errorMessage"); | |
} 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) { | |
// Handle exception | |
echo "An error occurred: " . $e->getMessage(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment