通過http URL 獲取圖片流 轉為字節數組


 

 通過http URL 獲取圖片流 轉為字節數組

 讀取本地文件轉為數組

 

 

/**
     * 獲取 文件 流
     * @param url
     * @return
     * @throws IOException
     */
    private byte[] getFile(String url) throws IOException{
        URL urlConet = new URL(url);
        HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();    
        con.setRequestMethod("GET");    
        con.setConnectTimeout(4 * 1000);    
        InputStream inStream = con .getInputStream();    //通過輸入流獲取圖片數據    
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
        byte[] buffer = new byte[2048];    
        int len = 0;    
        while( (len=inStream.read(buffer)) != -1 ){    
            outStream.write(buffer, 0, len);    
        }    
        inStream.close();    
        byte[] data =  outStream.toByteArray(); 
        return data;
    }

 

/**
     * 讀取 本地文件,轉為字節數組
     * @param url 本地文件路徑
     * @return
     * @throws IOException
     */
    private byte[] getImage(String url) throws IOException{
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(url));
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);    
       
        byte[] temp = new byte[2048];        
        int size = 0;        
        while ((size = in.read(temp)) != -1) {        
            out.write(temp, 0, size);        
        }        
        in.close();  
        byte[] content = out.toByteArray();  
        return content;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM