Microsoft Face API中的“解码错误,图像格式不受支持”

时间:2016-03-20 23:06:49

标签: java api face

我正在尝试使用Microsoft Face API。为此,我将以下代码作为示例(在本页末尾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;

但是我收到以下错误:

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

我用于测试的图像是这样的: http://www.huntresearchgroup.org.uk/images/group/group_photo_2010.jpg (通过快速搜索在互联网上找到)

它尊重Microsoft设置的所有请求,大小和格式......如果我在网站中使用它,它可以正常工作https://www.projectoxford.ai/demo/face#detection

从我的字节数组转换为base64中的字符串的String body也可以,我在这个网站上测试它:http://codebeautify.org/base64-to-image-converter

错误信息非常简单,但我看不到我在哪里。任何人都可能知道这个问题是什么?

更新

变量img

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

4 个答案:

答案 0 :(得分:2)

我设法发现了问题......而不是:

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

我需要这样做:

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

我认为文档已经过时了......

答案 1 :(得分:1)

我做了以下更改。我没有发送编码图像,而是发送图像的URL。

request.setHeader("Content-Type", "application/json");
request.setHeader("Ocp-Apim-Subscription-Key", "{YOUR_FACES_API_KEY}");

StringEntity reqEntity = new StringEntity("{ \"url\":\"http://www.huntresearchgroup.org.uk/images/group/group_photo_2010.jpg\" }");
request.setEntity(reqEntity);

这得到了答复:

[{"faceRectangle":{"top":878,"left":2718,"width":312,"height":312},"faceAttributes":{"gender":"male","age":28.5}},{"faceRectangle":{"top":593,"left":573,"width":310,"height":310},"faceAttributes":{"gender":"male","age":27.5}},{"faceRectangle":{"top":1122,"left":1014,"width":294,"height":294},"faceAttributes":{"gender":"female","age":27.7}},{"faceRectangle":{"top":915,"left":1773,"width":277,"height":277},"faceAttributes":{"gender":"female","age":36.7}},{"faceRectangle":{"top":566,"left":1276,"width":269,"height":269},"faceAttributes":{"gender":"male","age":40.7}},{"faceRectangle":{"top":677,"left":2134,"width":257,"height":257},"faceAttributes":{"gender":"female","age":35.2}}]

将尽快发送编码图像。将相应更新此帖子。

编辑:

从网址下载图片

String base64Img = null;
byte[] bytes = null;
String imgBinaryString = null;
String base64ImgBinaryString = null;
try {
    URL url = new URL("http://www.businessstudynotes.com/wp-content/uploads/2015/09/Role-of-Group.jpg");
    //"http://www.huntresearchgroup.org.uk/images/group/group_photo_2010.jpg");
    BufferedImage image = ImageIO.read(url);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
    bytes = baos.toByteArray();
    StringBuilder sb = new StringBuilder();
    for (byte by: bytes)
        sb.append(Integer.toBinaryString(by & 0xFF));
    imgBinaryString = sb.toString();

    base64Img = Base64.getEncoder().encodeToString(bytes);
    byte[] base64Bytes = base64Img.getBytes("UTF-8");
    sb = new StringBuilder();
    for (byte by: base64Bytes) {
        sb.append(Integer.toBinaryString(by & 0xFF));
    }
    base64ImgBinaryString = sb.toString();

} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    System.out.println("Download issue");
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    System.out.println("ImageIO issue");
    e.printStackTrace();
}

imgBinaryString包含图像的二进制表示; base64ImgBinaryString包含图像的Base 64表示的二进制表示。

上传此图片......

URI uri = builder.build(); // builder = new URIBuilder("https://api.projectoxford.ai/face/v1.0/detect");
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Ocp-Apim-Subscription-Key", "{YOUR_FACES_API_KEY");

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

HttpResponse response = httpclient.execute(request);

StringEntity设置为imgBinaryStringbase64ImgBinaryString会产生相同的回复......

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

现在,好东西。这有效......

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

其中bytes是图像的字节数组;但是Base64的表示并不起作用。有人真的需要更新文档。

答案 2 :(得分:0)

您可以查看CognitiveJ,这是一个处理通信的开源库。与MS的交互面临API。如果您不想使用该库,那么您可以查看代码以查看REST API所期望的内容。

(披露 - 我是图书馆的作者)。

答案 3 :(得分:0)

import okhttp3.*;

import java.io.File;
import java.io.IOException;


public class Main {


    public static void main(String[] args) {
        try {
            doRequest();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void doRequest() throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"),
                new File(".//src//main//java//Archivo_001.png"));

        Request request = new Request.Builder()
                .url("https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise")
                .post(body)
                .addHeader("Ocp-Apim-Subscription-Key", "1d88f949af3443ea8cc16b7146bd7501")
                .addHeader("Content-Type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());

    }


}