How to crop an image to the face in PHP

Cloudmersive
1 min readAug 2, 2019

--

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:

And our round cropped output:

That’s it, all done.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet