請求URL圖片,保存在本地。簡單代碼

    //創建緩存路徑
        //Environment.getExternalStorageDirectory()獲取手機內存卡根路徑
        cache=new File(Environment.getExternalStorageDirectory(),
                "com.xinshi.android.face.demo/batch_import_person_images");
        if(!cache.exists()){
            cache.mkdirs();
        }
        //耗時操作都要放在子線程操作
        //開啓子線程獲取輸入流
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn=null;
                InputStream is=null;
                try {
                    URL url=new URL(imgPath);
                    //開啓連接
                    conn=(HttpURLConnection) url.openConnection();
                    //設置連接超時
                    conn.setConnectTimeout(5000);
                    //設置請求方式
                    conn.setRequestMethod("GET");
                    //conn.connect();
                    if(conn.getResponseCode()==200){
                        is=conn.getInputStream();
                        Bitmap b=BitmapFactory.decodeStream(is);
                        //把輸入流轉化成bitmap格式,以msg形式發送至主線程
                        Message msg=new Message();
                        msg.obj=b;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    try {
                        //用完記得關閉
                        is.close();
                        conn.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

 

////////////////////////////////////////////////////////////////////////////////////////////////

 

   private String imgPath="http://pic.nipic.com/2007-11-09/200711912453162_2.jpg";
    private File cache;//緩存路徑

    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //顯示
            Bitmap b=(Bitmap)msg.obj;
//            iv_pic.setImageBitmap(b);
            //保存至本地
            File imgFile=new File(cache,"name.jpg");
            //添加到底庫
            try {
                BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(imgFile));
                b.compress(Bitmap.CompressFormat.JPEG,80,bos);
                bos.flush();
                bos.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }
    });
 

 

 

 

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