图片转二进制

 

 

 

    public static byte[] toBinary(String filename) throws IOException{
        if(!ParameterChecker.startWithProtocol(filename)){
            if(filename.startsWith("/")){
                filename = WebUtils.getAbsolutePath(filename);
            }
            return toBinary(new File( filename ));
        }
        
        URL url = new URL(filename);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = connection.getInputStream();
        return toBinary(inputStream);
    }
    
    public static byte[] toBinary(File file) throws IOException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        return toBinary(bufferedInputStream);
    }
    
    public static byte[] toBinary(InputStream inputStream) throws IOException{
        int len = inputStream.available();
        byte[] bytes = new byte[len];
        int r = inputStream.read(bytes);
        if (len != r) {
            bytes = null;
            throw new IOException("读取文件不正确");
        }
        inputStream.close();
        return bytes;
    }

 

posted @ 2015-05-28 13:50  rubekid  阅读(294)  评论(0编辑  收藏  举报