Created
November 14, 2023 04:09
-
-
Save BackgroundCut/20fa54b0eabb6ced924fb9a02dfa45f7 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://api.backgroundcut.co/v2/cut/"; | |
$apiKey = 'YOUR_API_KEY'; | |
$imagePath = "/path/to/file.jpg"; | |
$localOutputFilename = "/path/to/output.webp"; | |
// Request parameters | |
$requestParameters = [ | |
'quality' => 'medium', | |
'return_format' => 'webp', | |
'max_resolution' => '12000000' // 12 MegaPixels (for example 4000 * 3000) | |
]; | |
// Open image file | |
$imageFile = new CURLFile($imagePath); | |
// Initialize cURL | |
$ch = curl_init($apiEndpoint); | |
// Set cURL options | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, [ | |
'image_file' => $imageFile | |
] + $requestParameters); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, [ | |
'Authorization: ' . $apiKey | |
]); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 20); // 20 seconds | |
// Execute cURL session | |
$response = curl_exec($ch); | |
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
// Error handling | |
if ($httpStatusCode == 200) { | |
// Success: Save the returned image | |
file_put_contents($localOutputFilename, $response); | |
} elseif ($httpStatusCode >= 400 && $httpStatusCode < 500) { | |
// Client error | |
$errorResponse = json_decode($response, true); | |
$errorMessage = $errorResponse['error'] ?? 'No error message provided'; | |
throw new Exception("Client error. Status Code: $httpStatusCode. Error Message: $errorMessage"); | |
} elseif ($httpStatusCode >= 500 && $httpStatusCode < 600) { | |
// Server error | |
throw new Exception("Server error. Status Code: $httpStatusCode"); | |
} else { | |
// Unexpected response | |
throw new Exception("Unexpected response. Status Code: $httpStatusCode"); | |
} | |
// Close cURL session and handle errors | |
if (curl_errno($ch)) { | |
throw new Exception("cURL error occurred: " . curl_error($ch)); | |
} | |
curl_close($ch); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment