lulas lulas - 6 months ago 104
Java Question

"Decoding error, image format unsupported" in Microsoft Face API

I'm trying to use Microsoft Face API. For that I have the following code that was given by Microsoft as a sample (at the end of this page https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236):

HttpClient httpclient = HttpClients.createDefault();

try {
URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/face/v1.0/detect");

builder.setParameter("returnFaceId", "false");
builder.setParameter("returnFaceLandmarks", "false");
builder.setParameter("returnFaceAttributes", "age,gender");

URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Ocp-Apim-Subscription-Key", "...");

String body = Base64.encodeBase64String(img);

StringEntity reqEntity = new StringEntity(body);
request.setEntity(reqEntity);

HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();

if (entity != null) {
System.out.println(EntityUtils.toString(entity));
return JsonParser.parse(EntityUtils.toString(entity));
}
} catch (URISyntaxException | IOException | ParseException e) {
System.out.println(e.getMessage());
}

return null;


but I get the following error:

{"error":{"code":"InvalidImage","message":"Decoding error, image format unsupported."}}


The image that I am using for tests is this one:
http://www.huntresearchgroup.org.uk/images/group/group_photo_2010.jpg
(found it on the internet in a quick search)

It respect all the requisits set by Microsoft, size and format... If I use it in the site it works https://www.projectoxford.ai/demo/face#detection

The
String body
from the convertion of my array of bytes to a string in base64 is also ok, I test it in this website: http://codebeautify.org/base64-to-image-converter

The error message it's quite simple, but I fail to see where I am worng. Anyone might know whats the problem?

UPDATE

The variable
img
:

img = Files.readAllBytes(Paths.get(imgPath));

Answer

I managed to discover the problem... Instead of:

String body = Base64.encodeBase64String(img);
StringEntity reqEntity = new StringEntity(body);
request.setEntity(reqEntity);

I needed to do:

ByteArrayEntity reqEntity = new ByteArrayEntity(img, ContentType.APPLICATION_OCTET_STREAM);
request.setEntity(reqEntity);

I think that the Documentation is outdated...