android網絡獲取圖片並保存在本地和獲取手機SD卡中的圖片顯示到ImageView上及利用代碼刪除圖片


獲取網絡上的圖片有三步:

一、設置連接網絡的權限和寫入讀取SD卡的權限。二、網絡訪問獲得數據流。 三、在SD卡中創建文件夾將數據流轉成圖片格式存儲。

注意:response.getEntity().getContent()方法,而此方法只能調用一次。否則會報錯:java.lang.IllegalStateException: Content has been consumed。

manifest.xml

賦予權限,注意:在<application...>application>前添加

 <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

MainActivity.java

獲得網絡圖片的數據流

 HttpGet header = new HttpGet("你服務器的圖片地址");
                 //自定義的Cookie(服務器返回)
                 //header.setHeader("Cookie", "key");
                 HttpResponse headerresponse = httpclient.execute(header); //                
                // headerresponse.getEntity().getContent(); 只能用一次否則會報錯Content has been consumed  
                 InputStream headerin =
                 headerresponse.getEntity().getContent();// 服務器返回的數據
                 bitmap = BitmapFactory.decodeStream(headerin);               
                 if (bitmap != null) {                
                 saveBitmap(bitmap);// display image
                 }                 
                 headerin.close();

保存的位置:

    /**
         * 保存方法
         * 
         * @throws IOException
         */
        public void saveBitmap(Bitmap bitmap) throws IOException {
//更改的名字 String imageName
="w"+".jpg"; String headPath=android.os.Environment.getExternalStorageDirectory()+ "/"+"msg"+"/"+"head"; File headDir=new File(headPath); if(!headDir.exists()){ headDir.mkdirs(); } System.out.println(headPath+"\n"+headDir); FileOutputStream headFos=null; File headFile=null; try{ //重命名並保存 headFile=new File(headPath,imageName); headFile.createNewFile(); headFos=new FileOutputStream(headFile); bitmap.compress(CompressFormat.JPEG, 100, headFos); headFos.flush(); }catch(Exception e){ e.printStackTrace(); }finally{ if(headFos!=null){ try { headFos.close(); } catch (IOException e) { e.printStackTrace(); } } } }

 擴展:把手機SD卡中的圖片顯示到ImageView上。

String headPath = android.os.Environment.getExternalStorageDirectory()
            + "/" + "msg" + "/" + "head/";
Bitmap bmpDefaultPic;

ImageView imgv_img = (ImageView) findViewById(R.id.imageView1);
bmpDefaultPic = BitmapFactory.decodeFile(
                    headPath +"圖片名" + ".jpg", null);
imgv_img.setImageBitmap(bmpDefaultPic);

 利用代碼刪除本地圖片:

File file =new File(headPath+"/"+"圖片名"+".JPG");
file.delete();

 


免責聲明!

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



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