三级缓存02

作者: 没钱一定要骚 | 来源:发表于2017-12-21 14:18 被阅读0次

    //缓存到手机SD卡,封装成一个类

    public class LocalCache {

    public void putImage(String imageUrl, Bitmap bitmap) throws Exception {

    String newImage = MD5Unit.encode(imageUrl);

    Log.e("newImage", newImage);

    File file = new File(Environment.getExternalStorageDirectory() + "/BCache/" + newImage);

    Log.e("看看目录结构", file.getAbsolutePath());

    File parentFile = file.getParentFile();

    Log.e("看看文件的父目录", parentFile.getAbsolutePath());

    if (!parentFile.exists()) {

    parentFile.mkdirs();

    }

    FileOutputStream fos = new FileOutputStream(file);

    //Bitmap可以直接跟IO流就行直接交互

    //compress 有三个参数,参数1:图片格式 参数2:对原图片进行压缩,参数3:流

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

    Log.e("-----", "图片写入成功 66哒");

    fos.flush();

    fos.close();

    }

    public Bitmap getImage(String imageUrl) throws Exception {

    String newImage = MD5Unit.encode(imageUrl);

    File file = new File(Environment.getExternalStorageDirectory() + "/BCache/" + newImage);

    InputStream in = new FileInputStream(file);

    Log.e("获取图片", "成功么么哒");

    return BitmapFactory.decodeStream(in);

    }

    }

    //获取到手机内存中,封装成一个类

    public class PhoneCache { private LruCachemLru; private Context mContext; public PhoneCache(Context context) { this.mContext = context; //得到一个可以管理手机内存操作者的类 ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); //得到手机内存空间大小,单位是m int memoryClass = manager.getMemoryClass(); Log.e("memoryClass", memoryClass + "m"); //因为等会我们实例化LRUCache是构造方法里面参数是字节类型所有要吧m转换成b int maxSize = memoryClass * 1024 * 1024 / 8; Log.e("maxSize", maxSize + "by"); mLru = new LruCache(maxSize) {

    @Override

    protected int sizeOf(String key, Bitmap value) {

    //计算图片的大小

    return value.getRowBytes() * value.getHeight();

    }

    };

    }

    //存放图片和得到图片

    public void putImage(String url, Bitmap b) {

    mLru.put(url, b);

    Log.e("存放", "存放成功");

    }

    public Bitmap getImage(String url) {

    Log.e("获取", "获取成功");

    return mLru.get(url);

    }

    }

    相关文章

      网友评论

        本文标题:三级缓存02

        本文链接:https://www.haomeiwen.com/subject/mbhawxtx.html