android開發——獲取網絡圖片



 

//通過地址獲取bitmap
    public Bitmap getBitmap(String path) {
        Bitmap bitmap = null;
        try {
            //封裝url
            URL url = new URL(path);
            //獲得httpurl連接對象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //設置連接超時
            connection.setConnectTimeout(5*1000);
            //設置請求方法
            connection.setRequestMethod("GET");
            //判斷請求狀態碼是否連接成功
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                //bitmapfactory可以有多種生存bitmap的方法
                bitmap = BitmapFactory.decodeStream(is);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    //獲得字節數組
    public void getBytesByIs(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len ;
        byte[] data = new byte[1024];
        while((len = is.read(data))!=-1){
            bos.write(data, 0, len);
        }
        byte[] bytes = bos.toByteArray();
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章