Permalink
Browse files

Merge pull request #25 from alex-topface/crop-face

added cropFaceToJpeg method
  • Loading branch information...
2 parents 7311144 + 7538680 commit b016273ceceacd85562bbc50384fbabc947fe525 @mauricesvay committed Jan 26, 2016
Showing with 44 additions and 3 deletions.
  1. +13 −0 Exception/NoFaceException.php
  2. +30 −2 FaceDetector.php
  3. +1 −1 composer.json
@@ -0,0 +1,13 @@
+<?php
+
+/**
+ * Throws exception if face was not detected in `faceDetect` call.
+ */
+
+namespace svay\Exception;
+
+use Exception;
+
+class NoFaceException extends Exception {
+
+}
View
@@ -22,6 +22,7 @@
namespace svay;
use Exception;
+use svay\Exception\NoFaceException;
class FaceDetector
{
@@ -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')
{
@@ -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);
View
@@ -14,6 +14,6 @@
"ext-gd": "*"
},
"autoload": {
- "classmap": ["FaceDetector.php"]
+ "classmap": ["FaceDetector.php", "Exception/"]
}
}

0 comments on commit b016273

Please sign in to comment.