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+" "+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();
                          作者:xubuhang                出处:http://www.cnblogs.com/xubuhang/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 

 
【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/xubuhang/p/4149627.html