Bitmap图片的三级缓存

这是向本地缓存的外部类
public class LoadFileUtils {
private static LoadFileUtils loadFileUtils = new LoadFileUtils();
private LoadFileUtils (){}

// 向本地保存图片
public void setLoadFile(String name, Bitmap bitmap){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+name);
Log.i(“WL”, "setLoadFile: "+“本地文件地址”+file.getAbsolutePath());

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }finally {
        if (fileOutputStream != null){
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

// 从 本地读取图片
public Bitmap getLoadFile(String name){
File file = new File(Environment.getExternalStorageDirectory()+"/"+name);
if (file.length() <= 0){
Log.i(“WL”, "getLoadFile: "+“无内容”);
return null;
}
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

public static LoadFileUtils getInstance(){
    return loadFileUtils;
}

}

// 这是内存缓存外部类

public class LruCacheUtils {

public static LruCacheUtils lurCache = null;

long maxMemory = Runtime.getRuntime().maxMemory();// 获取分配给APP的内存大小
LruCache<String,Bitmap> lruCacheMap;

public LruCacheUtils(){
    Log.i("WL", "LruCacheUtils: "+" 初始化内utils");

    lruCacheMap = new LruCache<String, Bitmap>((int) (maxMemory/8)){
        // 返回每个对象的大小
        @Override
        protected int sizeOf(String key, Bitmap value) {
            int byteCount = ((Bitmap) value).getByteCount();
            return byteCount;
        }
    };
}

// lrcCache 可以将最近最少使用的对象回收掉, 从而保证内存不会超出范围
// lru : least recentlly used 最近最少使用算法

// 写缓存
public void setMemoryCache(String url,Bitmap bitmap){
lruCacheMap.put(url,bitmap);
Log.i(“WL”, "setMemoryCache: "+lruCacheMap.get(url).getByteCount());
}
// 读缓存
public Bitmap getMemoryCache(String url){
return lruCacheMap.get(url);

}
public static LruCacheUtils getLurCacheInstance(){ // 懒汉式单例
if (lurCache == null){
synchronized (LruCacheUtils.class){
if (lurCache == null){
lurCache = new LruCacheUtils();
}
}
}
return lurCache;
}
}
// 这是网络加载外部类 使用的是 Thread线程

public class NetCacheUtils {

// 启动线程的方法 并将 图片的 网络地址 给传过来
public void begin(String url){
new BitmapAsyncTask(url).start();
}

private class BitmapAsyncTask extends Thread{

private String imgUrl;
    public BitmapAsyncTask(String url) {
        this.imgUrl = url;
    }
    @Override
    public void run() {
        super.run();

        HttpURLConnection connection = null;
        try {
         URL url = new URL(imgUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(5000);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == 200){
                InputStream inputStream = connection.getInputStream();
                int available = inputStream.available();
                Log.i("aaa", "run: "+available);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

               getData.getbitmap(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

private getData getData;

public void setGetData(NetCacheUtils.getData getData) {
    this.getData = getData;
}

public interface getData{
    void getbitmap(Bitmap bitmap);
}

}

// activity代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener, NetCacheUtils.getData {

private Button loacImg;
private SimpleDraweeView simple_img;   //  这里我用了Fresco第三方的图片加载控件  换做ImageView 也一样
private String imgUrl = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3034041308,2252600183&fm=27&gp=0.jpg"; // 图片的网络地址
private ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
}

private void initView() {
    loacImg = (Button) findViewById(R.id.loacImg);
    simple_img = (SimpleDraweeView) findViewById(R.id.simple_img);

    loacImg.setOnClickListener(this);
    img = (ImageView) findViewById(R.id.img);
    img.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.loacImg:
            // 先存 内存中 读取
         Bitmap bitmap = LruCacheUtils.getLurCacheInstance().getMemoryCache(imgUrl);
           if (bitmap == null){ // 如果内存中读取为空, 那么就去 本地存储中拿
              bitmap = LoadFileUtils.getInstance().getLoadFile("abc.jpeg");
              if (bitmap == null){// 如果本地存储也没有,那么就去网路上加载
                  NetCacheUtils netCacheUtils = new NetCacheUtils();
                  netCacheUtils.setGetData(this);
                  netCacheUtils.begin(imgUrl);
              }else {
                  simple_img.setImageBitmap(bitmap);
                  Toast.makeText(MainActivity.this, "图片来自本地", Toast.LENGTH_SHORT).show();
              }

           }else {
                 simple_img.setImageBitmap(bitmap);
               LoadFileUtils.getInstance().setLoadFile("abc.jpeg",bitmap);
               Toast.makeText(MainActivity.this, "图片来自内存", Toast.LENGTH_SHORT).show();
           }

            break;
    }
}

// 这里使用了接口回调 将下载下来的bitmap 传过来
@Override
public void getbitmap(final Bitmap bitmap) {
// 如果请求成功 同时向内存和本地进行保存
LruCacheUtils.getLurCacheInstance().setMemoryCache(imgUrl,bitmap);
LoadFileUtils.getInstance().setLoadFile(“abc.jpeg”,bitmap);
// 因为那边是子线程下载 会调 的接口 所以我们要进行UI的更改应起runOnUiThread来对UI进行修改操作

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, "图片来自网络", Toast.LENGTH_SHORT).show();
            simple_img.setImageBitmap(bitmap);
            img.setImageBitmap(bitmap);
        }
    });

}

}

// 效果如下,
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的安卓图片三级缓存的工具类: ```java public class ImageLoader { private static final int MAX_MEMORY_CACHE_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8); private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; private static final int IO_BUFFER_SIZE = 8 * 1024; private static final String IMAGE_CACHE_DIR = "image_cache"; private static ImageLoader instance; private LruCache<String, Bitmap> memoryCache; private DiskLruCache diskCache; private ImageLoader(Context context) { initMemoryCache(); initDiskCache(context); } public static synchronized ImageLoader getInstance(Context context) { if (instance == null) { instance = new ImageLoader(context); } return instance; } private void initMemoryCache() { memoryCache = new LruCache<String, Bitmap>(MAX_MEMORY_CACHE_SIZE) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } }; } private void initDiskCache(Context context) { try { File cacheDir = getDiskCacheDir(context, IMAGE_CACHE_DIR); diskCache = DiskLruCache.open(cacheDir, BuildConfig.VERSION_CODE, 1, MAX_DISK_CACHE_SIZE); } catch (IOException e) { e.printStackTrace(); } } private File getDiskCacheDir(Context context, String uniqueName) { final String cachePath = context.getCacheDir().getPath(); return new File(cachePath + File.separator + uniqueName); } public void displayImage(final ImageView imageView, final String url) { imageView.setTag(url); Bitmap bitmap = getBitmapFromMemoryCache(url); if (bitmap != null) { imageView.setImageBitmap(bitmap); return; } AsyncTask.execute(new Runnable() { @Override public void run() { Bitmap bitmap = getBitmapFromDiskCache(url); if (bitmap != null) { addBitmapToMemoryCache(url, bitmap); if (imageView.getTag().equals(url)) { imageView.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } return; } try { bitmap = getBitmapFromUrl(url); addBitmapToMemoryCache(url, bitmap); addBitmapToDiskCache(url, bitmap); if (imageView.getTag().equals(url)) { imageView.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } } catch (IOException e) { e.printStackTrace(); } } }); } private Bitmap getBitmapFromMemoryCache(String key) { return memoryCache.get(key); } private void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemoryCache(key) == null) { memoryCache.put(key, bitmap); } } private Bitmap getBitmapFromDiskCache(String key) { try { DiskLruCache.Snapshot snapshot = diskCache.get(key); if (snapshot != null) { InputStream inputStream = snapshot.getInputStream(0); return BitmapFactory.decodeStream(inputStream); } } catch (IOException e) { e.printStackTrace(); } return null; } private void addBitmapToDiskCache(String key, Bitmap bitmap) { try { DiskLruCache.Editor editor = diskCache.edit(key); if (editor != null) { OutputStream outputStream = editor.newOutputStream(0); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); editor.commit(); } } catch (IOException e) { e.printStackTrace(); } } private Bitmap getBitmapFromUrl(String urlString) throws IOException { InputStream inputStream = null; try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); inputStream = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); return BitmapFactory.decodeStream(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } } } ``` 使用该类加载图片只需调用 `displayImage()` 方法,该方法会先从内存缓存中查找图片,如果找到则直接显示在 ImageView 上,否则会异步去磁盘缓存中查找图片,如果找到则添加到内存缓存,并显示在 ImageView 上,否则会异步去网络上下载图片,下载完成后添加到内存缓存和磁盘缓存,并显示在 ImageView 上。该方法支持传入任何类型的 ImageView,包括 VideoView。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值