java opencv读取url中的图片(只有一张,情况特殊),返回Mat形式

采用imdecode函数

        String strUrl = "http://...;
        InputStream is = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        URL url = null;
        try{
            url = new URL(strUrl);
        }catch (MalformedURLException e1){
            e1.getMessage();
            return -1;
        }
        try{
            is = url.openStream();
        }catch (IOException e2){
            e2.getMessage();
            return -1;
        }
        byte[] buffer = new byte[8192];
        try {
            int bytesRead = 0;
            while((bytesRead = is.read(buffer,0,8192))!=-1){
                os.write(buffer,0,bytesRead);
            }
        }catch (IOException e3){
            e3.getMessage();
            return -1;
        }
        try {
            is.close();
        }catch (IOException e4){
            e4.getMessage();
            return -1;
        }
        Mat encoded = new Mat(1, os.size(), CvType.CV_8U);
        encoded.put(0, 0, os.toByteArray());
        try {
            os.close();
        }catch (IOException e5){
            e5.getMessage();
            return -1;
        }
        //从内存中读,返回Mat形式
        Mat decoded = Highgui.imdecode(encoded, -1);
        encoded.release();
        return decoded;


猜你喜欢

转载自blog.csdn.net/mimi9919/article/details/77686436