Android에서 MS FACE API SDK의 최신버전을 사용하려면, minSDKVersion 이 22 이상이 되어야 합니다. 이걸 억지로 올리기 싫어서 해당 기능을 Rest API로 호출해 보았고 그 방법을 공유해 드립니다.
(If you are using the latest MS Face API on Android, "minSDKVersion" must be at least 22. I did not want to set it to 22 or higher, so I tried another method- Rest API !)
현재 MS나 인터넷에 있는 예제 대부분은 특정 서버상에 올라가 있는 얼굴 이미지의 경로를 파라메터로 전달합니다.
(Most examples set the parameters of the cloud to the path of the face image.)
이 예제는 로컬에 있는 이미지를 업로드 하여 그 결과를 가지고 오는 방법입니다.
(On the other hand, this example shows how to upload an image file to the Face API)
얼굴을 촬영한 JPG이미지를 octect-stream 으로 업로드 하고, 기타 필요한 파라메터를 추가하여 호출합니다.
(A method of uploading a JPG image with face shots to an octet stream, adding other required parameters, and then calling the API.)
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class FaceAPISupport extends Thread {
private String finURL;
private String handler_keyname;
private RequestBody body;
private String apikey;
//로컬에 저장되어 있는 얼굴을 촬영한 이미지 파일의 경로를 파라메터로 전달합니다.
public FaceAPISupport(String filepath) {
body = RequestBody.create(MediaType.parse("application/octet-stream"), new File(filepath));
handler_keyname = "Ocp-Apim-Subscription-Key"; //API 키를 위한 헤더 파라메터 이름
apikey = "<API 키 입력>";
String url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect"; //REST API 주소
/*
얻어오고 싶은 파라메터를 설정합니다. 자세한 내용은 아래링크를 참고하세요.
https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236
*/
finURL = url
+ "?returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
}
public Response callPost(String apikeyName, String apikey, String contentHeader, String url, RequestBody body) throws IOException {
Request request = new Request.Builder()
.url(url)
.addHeader(apikeyName, apikey)
.addHeader("Content-Type", contentHeader)
.post(body)
.build();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
return client.newCall(request).execute();
}
@Override
public void run() {
try {
Response response = callPost(handler_keyname, apikey, "application/octet-stream", finURL, body);
if (response.isSuccessful()) {
//결과는 아래 스트링에서 확인할 수 있습니다.
String jSonString = response.body().string();
}
}
catch (IOException e) {
}
}
}
//사용법
new FaceAPISupport(filePath).start();건투를 빕니다!