Azure Face API无法使用本地文件

时间:2018-03-08 23:51:32

标签: java azure face-api

我一直在尝试将图像从我的计算机发送到此API,但我只收到以下错误:{"error":{"code":"InvalidImageSize","message":"Image size is too small."}}

我的代码如下。 我有一个PostRequestClass用这个方法:

public void sendImageRequest(String imagePath) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        File file = new File(imagePath);
        FileEntity reqEntity = new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(false);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            this.responseResult = EntityUtils.toString(entity);
        }
    } catch(Exception e) {
        System.out.println(e.getMessage());
    }   
}

在我的主要是这一个:

public class Test {
    public static void main(String[] args) throws URISyntaxException {
        PostRequest p = new PostRequest(
          "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceAttributes=emotion"
        );
        p.addHeader("Content-Type", "application/octet-stream");
        p.addHeader("Ocp-Apim-Subscription-Key", "my-api-key");
        p.sendImageRequest("/Users/user/Desktop/image.jpg");
        System.out.println(p.getResponseResult());           
    }
}

2 个答案:

答案 0 :(得分:1)

我用以下代码解决了它:

public void sendImageRequest(String imagePath) {
    try {
        HttpClient httpClient = new DefaultHttpClient();

        File file = new File(imagePath);
        FileInputStream fileInputStreamReader = new FileInputStream(file);
        byte[] bytes = new byte[(int)file.length()];
        fileInputStreamReader.read(bytes);            
        ByteArrayEntity reqEntity = new ByteArrayEntity(bytes, ContentType.APPLICATION_OCTET_STREAM);
        request.setEntity(reqEntity);

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            this.responseResult = EntityUtils.toString(entity);
        }
    } catch(Exception e) {
        System.out.println(e.getMessage());
    }   
}

答案 1 :(得分:1)

  1. 转到https://azure.microsoft.com/en-us/services/cognitive-services/face/,然后点击" API参考"。

  2. 您将转到Face API参考页面https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236

  3. Face API文档说明支持JPEG,PNG,GIF(第一帧)和BMP格式。允许的图像文件大小为1KB到4MB。"

    在标题" JSON"中返回的错误代码和消息下, 它说," InValidImageSize"表示"有效图像文件大小应大于或等于1KB。"