Search code examples
javaazureface-api

Azure Face API not working with local file


I've been trying to send an image from my computer to this API but I only get the following error: {"error":{"code":"InvalidImageSize","message":"Image size is too small."}}

My code is the following. I have a PostRequestClass with this method:

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());
    }   
}

And on my Main is this one:

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());           
    }
}

Solution

  • I solved it with the following code:

    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());
        }   
    }