How to crop an image to the face in PHP

Here is a quick demonstration of how to use one of our APIs to locate a face in a photo and then crop the image accordingly. Let’s start with a reference to our API in the library:

"require": {
"cloudmersive/cloudmersive_imagerecognition_api_client": "^1.4",
}

Then we simply call one of two methods: faceCropFirst (square crop) or faceCropFirstRound (round crop). Here is the code for a round crop:

<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\FaceApi(


new GuzzleHttp\Client(),
$config
);
$image_file = "/path/to/file"; // \SplFileObject | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
$result = $apiInstance->faceCropFirstRound($image_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling FaceApi->faceCropFirstRound: ', $e->getMessage(), PHP_EOL;
}
?>

Here is an example full image:

Image for post
Image for post

And our round cropped output:

Image for post
Image for post

That’s it, all done.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store