How to send bitmap to face detect azure api via http post

516 views Asked by At

In my Android app the user takes a photo via camera. It is then available as bitmap:

Bitmap photo = (Bitmap) data.getExtras().get("data");

This I want to send to Azure Face-detect API via http post. Currently I get it only to work with a given URL to a pic:

StringEntity reqEntity = new StringEntity("{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg\"}");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(request)

How to use the Bitmap photo to send it to azure?

1

There are 1 answers

0
Peter Pan On BEST ANSWER

According to the API reference of Azure Face Detect, you can use the API with application/octet-stream content type to pass the android bitmap as binary data.

As reference, here is my sample code.

String url = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect";
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/octet-stream")
request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");

// Convert Bitmap to InputStream
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
InputStream photoInputStream = new ByteArrayInputStream(baos.toByteArray());
// Use Bitmap InputStream to pass the image as binary data
InputStreamEntity reqEntity = new InputStreamEntity(photoInputStream, -1);
reqEntity.setContentType("image/jpeg");
reqEntity.setChunked(true);

request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);

Hope it helps.