图片的三级缓存

package animtest.com.example.e531.unit7_piccache_demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;

/**
 * Created by e531 on 2017/10/9.
 */
public class ImageCacheUtil {

    //内存缓存  基于linkedHaspMap  key是图片的url地址
    private LruCache<String,Bitmap>  mLruCache;

    public ImageCacheUtil(Context context){

        //得到当前应用程序的内存空间大小
        int maxMemory= (int) Runtime.getRuntime().maxMemory();
        int cacheSize=maxMemory/4;

        //进行初使化,需要指定缓存空间大小
        mLruCache=new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();//自定义返回的数据的大小
            }
        };
    }

    /**
     * 根据key得到图片
     * @param key  是图片的url地址
     * @return
     */
    public Bitmap getPicFromMemory(String key){
        Bitmap bitmap=null;
        try {
            //1.进行md5加密处理
            String imgKey=encode(key);
            //2.直接获取数据
            bitmap=mLruCache.get(imgKey);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存一张图片到内存缓存
     * @param key
     * @param bitmap
     */
    public void savePicToMemory(String key,Bitmap bitmap){

        try {
            //1.进行md5加密
            String imgKey=encode(key);
            //2.通过key得到editor对象
            mLruCache.put(imgKey,bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用缓存加载图片
     * @param imgUrl
     * @param img
     */
    public  void loadPic(String imgUrl,ImageView img){

        //1.从内存缓存获取
        Bitmap bitmap=getPicFromMemory(imgUrl);
        if(bitmap!=null){
            Log.d("zzz","从内存缓存中获取");
            //直接进行显示
            img.setImageBitmap(bitmap);
            return;
        }

        //3.从网络获取
        loadPicFromNet(imgUrl,img);
    }

    /**
     * 从网络上下载图片
     * @param url
     * @param imageView
     */
    public  void loadPicFromNet(final String imgUrl, final ImageView imageView){
        AsyncTask<Void,Void,Bitmap> mytask=new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                Bitmap bitmap=null;
                try {
                    URL url=new URL(imgUrl);
                    HttpURLConnection connection=(HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);

                    if(connection.getResponseCode()==200){
                        InputStream inputStream=connection.getInputStream();
                        bitmap= BitmapFactory.decodeStream(inputStream);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);

                if(bitmap!=null){
                    Log.d("zzz","从网络中获取");
                    //保存到内存缓存
                    savePicToMemory(imgUrl,bitmap);

                    //进行显示
                    imageView.setImageBitmap(bitmap);
                }
            }
        };
        mytask.execute();
    }

    /**
     * 把一个字符串以md5的放肆加密之后返回...
     * 因为url路径里面可能存在一些不可用的特殊字符,所以使用这种方式处理一下
     * @param string
     * @return
     * @throws Exception
     */
    private String encode(String string) throws Exception {
        byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }



}
  • 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、付费专栏及课程。

余额充值