基于Android的图片缓存处理

    从互联网下载展示的图片耗时耗流量,切换页面、重新进入应用等操作又会造成图片的重复下载,为达到一次一次下载多次利用节时节量的效果,特进行图片的缓存处理。

一、获取图片

    1、第一层:设置内存缓存便于listview页面变化或activity界面转换等情况时重复利用已下载的图片:利用LruCache键值对集合存储URL-Bitmap键值对,由自身的url取出集合中对应的bitmap值。

   private static LruCachecache=new  LruCache(5<<20){
   protected int sizeOf(String key, Bitmap value) {
    return value.getByteCount();
   };
  };

    2、第二层:设置本地外部存储缓存,便于内存缓存中没有此图片时的操作,例如重新进入APP。从指定的存储路径中取出图片。以下为从内存卡中存取图片的方法。

private final String path = Environment.getExternalStorageDirectory().getPath() + "/myyi18";

  public Bitmap useTheImage(String imageUrl) { 
      Bitmap bmpDefaultPic = null; 

      // 获得文件路径 
      String imageSDCardPath = path 
              + "/image/" 
              + imageUrl.substring(imageUrl.lastIndexOf("/") + 1, 
                      imageUrl.length()).toLowerCase(); 
      File file = new File(imageSDCardPath); 
      // 检查图片是否存在 
      if (!file.exists()) {
          return null; 
      } 
      bmpDefaultPic = BitmapFactory.decodeFile(imageSDCardPath, null); 

      if (bmpDefaultPic != null) { 
          return bmpDefaultPic; 
      } else {
          return null;
      }
  } 
  public void saveFile(Bitmap bm, String url) { 
      try { 

          // 获得文件名字 
          final String fileNa = url.substring(url.lastIndexOf("/") + 1, 
                  url.length()).toLowerCase(); 
          File file = new File(path + "/image/" + fileNa); 
          // 创建图片缓存文件夹 
          boolean sdCardExist = Environment.getExternalStorageState().equals( 
                  android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在 
          if (sdCardExist) { 
              File yiyao = new File(path); 
              File ad = new File(path + "/image"); 
              // 如果文件夹不存在 
              if (!yiyao.exists()) { 
                  // 按照指定的路径创建文件夹 
               yiyao.mkdir(); 
                  // 如果文件夹不存在 
              } else if (!ad.exists()) { 
                  // 按照指定的路径创建文件夹 
                  ad.mkdir(); 
              } 
              // 检查图片是否存在 
              if (!file.exists()) { 
                  file.createNewFile(); 
              } 
          } 

          BufferedOutputStream bos = new BufferedOutputStream( 
                  new FileOutputStream(file)); 
          //把bitmap转换成指定图片类型 放进流中  100 表示不压缩
          bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
          bos.flush(); 
          bos.close();
          System.out.println("保存在sd成功");
      } catch (Exception e) { 
         e.printStackTrace();
      } 
  }

  3、第三层,若以上两个地方都没有url对应的图片,则开启异步任务从网络上下载。异步任务下载图片略。

二、存储图片

    想通过以上第1、2种方式获取图片,那就需要往里面添加图片信息,即每次从网络下载的图片除了项目基本应用外还要存在cache集合中和本地外部存储中。

    若内存中没有相应图片而本地外部存储中有,则除了项目基本应用外还要存在cache集合中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值