Skip to content
This repository has been archived by the owner on Jan 18, 2020. It is now read-only.

Commit

Permalink
Merge pull request #25 from alex-topface/crop-face
Browse files Browse the repository at this point in the history
added cropFaceToJpeg method
  • Loading branch information
mauricesvay committed Jan 26, 2016
2 parents 7311144 + 7538680 commit b016273
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
13 changes: 13 additions & 0 deletions Exception/NoFaceException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

/**
* Throws exception if face was not detected in `faceDetect` call.
*/

namespace svay\Exception;

use Exception;

class NoFaceException extends Exception {

}
32 changes: 30 additions & 2 deletions FaceDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
namespace svay;

use Exception;
use svay\Exception\NoFaceException;

class FaceDetector
{
Expand All @@ -33,11 +34,13 @@ class FaceDetector

/**
* Creates a face-detector with the given configuration
*
*
* Configuration can be either passed as an array or as
* a filepath to a serialized array file-dump
*
*
* @param string|array $detection_data
*
* @throws Exception
*/
public function __construct($detection_data = 'detection.dat')
{
Expand Down Expand Up @@ -150,6 +153,31 @@ public function toJpeg()
imagejpeg($this->canvas);
}

/**
* Crops the face from the photo.
* Should be called after `faceDetect` function call
* If file is provided, the face will be stored in file, other way it will be output to standard output.
*
* @param string|null $outFileName file name to store. If null, will be printed to output
*
* @throws NoFaceException
*/
public function cropFaceToJpeg($outFileName = null)
{
if (empty($this->face)) {
throw new NoFaceException('No face detected');
}

$canvas = imagecreatetruecolor($this->face['w'], $this->face['w']);
imagecopy($canvas, $this->canvas, 0, 0, $this->face['x'], $this->face['y'], $this->face['w'], $this->face['w']);

if ($outFileName === null) {
header('Content-type: image/jpeg');
}

imagejpeg($canvas, $outFileName);
}

public function toJson()
{
return json_encode($this->face);
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@
"ext-gd": "*"
},
"autoload": {
"classmap": ["FaceDetector.php"]
"classmap": ["FaceDetector.php", "Exception/"]
}
}

0 comments on commit b016273

Please sign in to comment.