1818// [START vision_face_detection]
1919namespace Google \Cloud \Samples \Vision ;
2020
21+ // [START import_client_library]
2122use Google \Cloud \Vision \V1 \ImageAnnotatorClient ;
2223
24+ // [END import_client_library]
25+
2326// $path = 'path/to/your/image.jpg'
2427
25- function detect_face ($ path )
28+ function detect_face ($ path, $ outFile = null )
2629{
30+ // [START get_vision_service]
2731 $ imageAnnotator = new ImageAnnotatorClient ();
28-
32+ // [END get_vision_service]
33+
34+ // [START detect_face]
2935 # annotate the image
3036 $ image = file_get_contents ($ path );
3137 $ response = $ imageAnnotator ->faceDetection ($ image );
3238 $ faces = $ response ->getFaceAnnotations ();
39+ // [END detect_face]
3340
3441 # names of likelihood from google.cloud.vision.enums
3542 $ likelihoodName = ['UNKNOWN ' , 'VERY_UNLIKELY ' , 'UNLIKELY ' ,
@@ -55,5 +62,44 @@ function detect_face($path)
5562 print ('Bounds: ' . join (', ' ,$ bounds ) . PHP_EOL );
5663 print (PHP_EOL );
5764 }
65+
66+ # draw box around faces
67+ if ($ faces && $ outFile ) {
68+ $ imageCreateFunc = [
69+ 'png ' => 'imagecreatefrompng ' ,
70+ 'gd ' => 'imagecreatefromgd ' ,
71+ 'gif ' => 'imagecreatefromgif ' ,
72+ 'jpg ' => 'imagecreatefromjpeg ' ,
73+ 'jpeg ' => 'imagecreatefromjpeg ' ,
74+ ];
75+ $ imageWriteFunc = [
76+ 'png ' => 'imagepng ' ,
77+ 'gd ' => 'imagegd ' ,
78+ 'gif ' => 'imagegif ' ,
79+ 'jpg ' => 'imagejpeg ' ,
80+ 'jpeg ' => 'imagejpeg ' ,
81+ ];
82+
83+ copy ($ path , $ outFile );
84+ $ ext = strtolower (pathinfo ($ path , PATHINFO_EXTENSION ));
85+ if (!array_key_exists ($ ext , $ imageCreateFunc )) {
86+ throw new \Exception ('Unsupported image extension ' );
87+ }
88+ $ outputImage = call_user_func ($ imageCreateFunc [$ ext ], $ outFile );
89+ # [START highlight_image]
90+ foreach ($ faces as $ face ) {
91+ $ vertices = $ face ->getBoundingPoly ()->getVertices ();
92+ if ($ vertices ) {
93+ $ x1 = $ vertices [0 ]->getX ();
94+ $ y1 = $ vertices [0 ]->getY ();
95+ $ x2 = $ vertices [2 ]->getX ();
96+ $ y2 = $ vertices [2 ]->getY ();
97+ imagerectangle ($ outputImage , $ x1 , $ y1 , $ x2 , $ y2 , 0x00ff00 );
98+ }
99+ }
100+ # [END highlight_image]
101+ call_user_func ($ imageWriteFunc [$ ext ], $ outputImage , $ outFile );
102+ printf ('Output image written to %s ' . PHP_EOL , $ outFile );
103+ }
58104}
59105// [END vision_face_detection]
0 commit comments