Skip to content

Commit b016273

Browse files
committed
Merge pull request mauricesvay#25 from alex-topface/crop-face
added cropFaceToJpeg method
2 parents 7311144 + 7538680 commit b016273

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

Exception/NoFaceException.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
/**
4+
* Throws exception if face was not detected in `faceDetect` call.
5+
*/
6+
7+
namespace svay\Exception;
8+
9+
use Exception;
10+
11+
class NoFaceException extends Exception {
12+
13+
}

FaceDetector.php

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
namespace svay;
2323

2424
use Exception;
25+
use svay\Exception\NoFaceException;
2526

2627
class FaceDetector
2728
{
@@ -33,11 +34,13 @@ class FaceDetector
3334

3435
/**
3536
* Creates a face-detector with the given configuration
36-
*
37+
*
3738
* Configuration can be either passed as an array or as
3839
* a filepath to a serialized array file-dump
39-
*
40+
*
4041
* @param string|array $detection_data
42+
*
43+
* @throws Exception
4144
*/
4245
public function __construct($detection_data = 'detection.dat')
4346
{
@@ -150,6 +153,31 @@ public function toJpeg()
150153
imagejpeg($this->canvas);
151154
}
152155

156+
/**
157+
* Crops the face from the photo.
158+
* Should be called after `faceDetect` function call
159+
* If file is provided, the face will be stored in file, other way it will be output to standard output.
160+
*
161+
* @param string|null $outFileName file name to store. If null, will be printed to output
162+
*
163+
* @throws NoFaceException
164+
*/
165+
public function cropFaceToJpeg($outFileName = null)
166+
{
167+
if (empty($this->face)) {
168+
throw new NoFaceException('No face detected');
169+
}
170+
171+
$canvas = imagecreatetruecolor($this->face['w'], $this->face['w']);
172+
imagecopy($canvas, $this->canvas, 0, 0, $this->face['x'], $this->face['y'], $this->face['w'], $this->face['w']);
173+
174+
if ($outFileName === null) {
175+
header('Content-type: image/jpeg');
176+
}
177+
178+
imagejpeg($canvas, $outFileName);
179+
}
180+
153181
public function toJson()
154182
{
155183
return json_encode($this->face);

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,6 @@
1414
"ext-gd": "*"
1515
},
1616
"autoload": {
17-
"classmap": ["FaceDetector.php"]
17+
"classmap": ["FaceDetector.php", "Exception/"]
1818
}
1919
}

0 commit comments

Comments
 (0)