Ошибка декодирования, формат изображения не поддерживается Azure - PullRequest
0 голосов
/ 07 октября 2018

Я использую флеш-сервер на сервере.Я хочу прочитать изображение из мобильного приложения и отправить его на сервер для обнаружения лиц.

Это код Java (на стороне клиента) для отправки изображения в байтах -

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

    }

}

Этокод моего сервера -

def get_facial(data):
    face_api_url = 'https://southeastasia.api.cognitive.microsoft.com/face/v1.0/detect'

    # Set image_url to the URL of an image that you want to analyze.
    headers = {'Ocp-Apim-Subscription-Key': subscription_key,
    "Content-Type":"application/octet-stream"
    }
    params = {
        'returnFaceId': 'true',
        'returnFaceLandmarks': 'false',
        'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
        'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
    }
    response = requests.post(face_api_url, params=params, headers=headers, data=data)
    faces = response.json()
    res={}
    import pdb; pdb.set_trace()

    res["status"] = '200'
    res["num"] = str(len(faces))
    return res

@app.route('/facial',methods=['POST'])
def facial():
    import pdb; pdb.set_trace()
    data=bytes(request.get_data())
    res={}
    try:
        res = get_facial(data)
    except:
        res['status'] = '404'
    print(res)
    return json.dumps(res)

После проверки я отправил то же изображение из другого файла python и проверил размер данных.Это было 102564 байта и , это работает , но то же самое изображение, прочитанное и отправленное из кода Java, составляет 106208 байтов.Я не знаю, где именно ошибка.Любая помощь приветствуется !!: -)

1 Ответ

0 голосов
/ 08 октября 2018

Я нашел быстрое решение этой проблемы -

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

Я точно не знаю, почему не удается прочитать из imageio.Я предполагаю, что он также читает заголовки файлов jpg файла.

...