解码错误,图片格式不受支持的Azure

时间:2018-10-07 15:02:16

标签: android flask javax.imageio httpconnection azure-cognitive-services

我正在后端运行Flask服务器。我想从移动应用读取图像并将其发送到服务器以检测面部。

这是用于将图像作为字节发送的Java代码(客户端)-

cream

这是我的服务器代码-

public class client {
    public static void main(String [] args) throws Exception{

        String url = "http://127.0.0.1:8080/facial";
// 2. create obj for the URL class
        URL obj = new URL(url);
        // 3. open connection on the url
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type","image/jpeg");
        con.setDoInput(true);
        con.setDoOutput(true);


        try {

            System.out.println("Reading image from disk. ");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.flush();
            File file = new File("jpeg.jpg");
            BufferedImage image1 = ImageIO.read(file);

            ImageIO.write(image1, "jpg", baos);
            baos.flush();
            System.out.println(baos.size());
            byte[] bytes = baos.toByteArray();
            baos.close();

            System.out.println("Sending image to server. ");

            OutputStream out = con.getOutputStream();
            DataOutputStream image = new DataOutputStream(out);

            image.writeInt(bytes.length);
            image.write(bytes, 0, bytes.length);

            System.out.println("Image sent to server. ");

            image.close();
            // close the output stream
            out.close();

        }catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }

        // define object for the reply from the server
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        //Get response from server
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);
        // read in the response from the server
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
            System.out.println(inputLine);
        }
        // close the input stream
        in.close();

    }

}

检查后-我从另一个 python文件发送了相同图片,并检查了数据大小。它是102564字节,并且有效,但是 从Java代码读取和发送的同一图像为106208字节。我不知道错误在哪里。 任何帮助表示赞赏!!:-)

1 个答案:

答案 0 :(得分:1)

我找到了解决此问题的快速方法-

Path path = Paths.get("jpeg.jpg");
byte[] fileContents =  Files.readAllBytes(path);
image.write(fileContents, 0, fileContents.length);

我不完全知道为什么从imageio读取失败。我的猜测是它还会读取jpg文件的文件头。