Skip to content

Instantly share code, notes, and snippets.

@lyatziv
Created December 17, 2013 20:33
Show Gist options
  • Save lyatziv/8012110 to your computer and use it in GitHub Desktop.
Save lyatziv/8012110 to your computer and use it in GitHub Desktop.
Old bit of code that used Face.com API to auto crop images with just php.
<?php
// Face.com api licence
$FaceAPI_Key = '[enter your key]';
$FaceAPI_Secret = '[enter your secret]';
// Get image url
$imgSRC = urlencode($_GET['url']);
// cURL ALT method
$url = 'https://api.face.com/faces/detect.json';
// Image Parameters
$params = array('api_key' => $FaceAPI_Key,
'api_secret' => $FaceAPI_Secret,
'urls' => $imgSRC,
'detector' => 'Aggressive',
'attributes' => 'all');
$result = geturl($url, $params);
// Decode to an object
$imageData = json_decode($result);
// Results are in pixles
$width = $imageData->photos[0]->width; // full image width
$height = $imageData->photos[0]->height; // Full image height
// These are results
$X_face = 10 + $imageData->photos[0]->tags[0]->width; // Face Width % of full image. Add 10% for padding
$Y_face = 20 + $imageData->photos[0]->tags[0]->height; // Face Height % of full image. Add 20% for padding
$X_face = ceil($X_face / 100 * $width); // Convert Face width from % to pixels
$Y_face = ceil($Y_face / 100 * $height); // Convert Height width from % to pixels
$X_pos = $imageData->photos[0]->tags[0]->center->x; // face center X %
$Y_pos = $imageData->photos[0]->tags[0]->center->y; // face center Y %
$X_pos = ceil(($X_pos / 100 * $width)-($X_face/2)); // Convert Face X position from % to pixels
$Y_pos = ceil(($Y_pos / 100 * $height)-($Y_face/2)); // Convert Face Y position from % to pixels
// cURL Function
function geturl($url, $params) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params, null, '&'));
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
// Create image instances
$src = imagecreatefromjpeg(urldecode($imgSRC));
$dest = imagecreatetruecolor($X_face, $Y_face);
// Copy
imagecopy($dest, $src, 0, 0, $X_pos, $Y_pos, $X_face, $Y_face);
// Output and free from memory
header('Content-Type: image/jpeg');
imagegif($dest);
// Do what you want with $dest (eg: copy to cache)
// freeup memory
imagedestroy($dest);
imagedestroy($src);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment