We can use APIs or libraries in PHP for smart image cropping.
Use an API for Smart Cropping
We can use a pre-built API like Filestack.
You can learn about using API for Smart Image Cropping for Social Media in this article I wrote recently.
Smart Image Cropping for Social Media: Enhance Your Visual Content
I have also added a PHP code snippet for uploading an image and Smart Cropping with an API below:
PHP Code Snippet for Smart Cropping with Filestack API
<?php
// Replace with your Filestack API key
$apiKey = 'YOUR_API_KEY';
// File to upload
$filePath = 'path/to/your/image.jpg';
// Filestack upload URL
$uploadUrl = "https://upload.filestackapi.com/api/store/S3?key={$apiKey}";
// Use cURL to upload the file
$ch = curl_init($uploadUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'fileUpload' => new CURLFile($filePath),
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$responseData = json_decode($response, true);
$fileHandle = $responseData['handle'];
// Filestack smart cropping URL
$smartCropUrl = "https://cdn.filestackcontent.com/smart_crop=width:400,height:400,mode:face/{$fileHandle}";
echo "Uploaded successfully. Access your smart-cropped image here:\n";
echo $smartCropUrl;
} else {
echo "File upload failed. HTTP Code: $httpCode\n";
echo "Response: $response\n";
}
?>
Steps Explained:
Upload the Image:
Get the File Handle:
Generate Smart Cropping URL:
smart_crop=width:400,height:400,mode:face
Access Cropped Image:
Using API is convenience and we can ensure the accuracy and scalability.