自己实现图片三级缓存

直接上代码:
BitmapUtils类:

public class BitmapUtils {
    //上下文
    Context context;
    //图片缓存地址
    private final static String CACHE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/bitmapcache";
    //图片缓存目录
    private File cacheDir = new File(CACHE_DIR);
    private Map<String, SoftReference<Bitmap>> map = new HashMap<String, SoftReference<Bitmap>>();
    //图片内存缓存所占用的内存大小
    int maxSize = (int) (Runtime.getRuntime().maxMemory() / 8);
    private LruCache<String, Bitmap> images = new LruCache<String, Bitmap>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ImageViewBitmap imageViewBitmap = (ImageViewBitmap) msg.obj;
                    imageViewBitmap.imageView.setImageBitmap(imageViewBitmap.bitmap);
                    break;
            }

        }
    };

    public BitmapUtils(Context context) {
        this.context = context;
        if (!cacheDir.exists()) {
            //创建
            cacheDir.mkdirs();
        }
    }

    public void display(ImageView imageView, String path) {
        //内存加载
        Bitmap bitmap = loadMemory(path);
        Log.i("xxx", bitmap.toString());
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            //sdcard加载
            bitmap = loadSD(path);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                //网络加载
                loadInternet(imageView, path);
            }
        }


    }

    //内存加载
    private Bitmap loadMemory(String path) {
        /*SoftReference<Bitmap> bitmapSoftReference = map.get(path);
        if (bitmapSoftReference != null) {
            Bitmap bitmap = bitmapSoftReference.get();
            return bitmap;
        }
        return null;*/
        //获取
        Bitmap bitmap = images.get(path);

        return bitmap;
    }

    //加载本地
    private Bitmap loadSD(String path) {
        String name = getFileName(path);
        File file = new File(cacheDir, name);
        if (file.exists()) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            int inSimpleSize = inSimpleSize(options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = inSimpleSize;
            //加载图片所占的像素内存是可以回收
            options.inInputShareable = true;
            options.inPurgeable = true;
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            //把加载的图片放入内存中
           /* SoftReference<Bitmap> value = new SoftReference<Bitmap>(bitmap);
            map.put(path, value);*/
            //保存
            images.put(path, bitmap);
            return bitmap;
        }
        return null;

    }

    //计算图片的缩放比例
    private int inSimpleSize(BitmapFactory.Options options) {
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int widthPixels = displayMetrics.widthPixels;
        int heightPixels = displayMetrics.heightPixels;
        //计算缩放比例
        int scaleX = outWidth / widthPixels;
        int scaleY = outHeight / heightPixels;
        int simpleSize = scaleX > scaleY ? scaleX : scaleY;
        if (simpleSize == 0) {
            simpleSize = 1;
        }

        return simpleSize;
    }

    //加载网络图片
    private void loadInternet(ImageView imageView, String path) {

        new Thread(new DownloadBitmapTask(imageView, path)).start();


    }

    private class DownloadBitmapTask implements Runnable {
        ImageView imageView;
        String path;
        private InputStream inputStream;
        private FileOutputStream fos;

        public DownloadBitmapTask(ImageView imageView, String path) {
            this.imageView = imageView;
            this.path = path;
        }

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 3000);
            HttpGet get = new HttpGet(path);
            try {
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {
                    inputStream = response.getEntity().getContent();
                    String name = getFileName(path);
                    //保存到sdcard
                    File file = new File(cacheDir, name);
                    fos = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    Bitmap bitmap = loadSD(name);
                    ImageViewBitmap imageViewBitmap = new ImageViewBitmap(imageView, bitmap);
                    Message message = Message.obtain(handler, 0, imageViewBitmap);
                    message.sendToTarget();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    //获取图片名字
    private String getFileName(String path) {
        return Md5Utils.encode(path) + ".jpg";
    }

    //ImageView转换成Bitmap
    private class ImageViewBitmap {
        ImageView imageView;
        Bitmap bitmap;

        public ImageViewBitmap(ImageView imageView, Bitmap bitmap) {
            super();
            this.imageView = imageView;
            this.bitmap = bitmap;
        }
    }
}

Md5Utils加密工具类:

public class Md5Utils {
    public static String encode(String password){
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer sb = new StringBuffer();
            for(byte b : result){
                int number = (int)(b & 0xff) ;
                String str = Integer.toHexString(number);
                if(str.length()==1){
                    sb.append("0");
                }
                sb.append(str);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            //can't reach
            return "";
        }
    }
}

代码中使用:

public class MainActivity extends AppCompatActivity {
    String url = "http://d.hiphotos.baidu.com/zhidao/pic/item/72f082025aafa40fe871b36bad64034f79f019d4.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView iv = (ImageView) findViewById(R.id.iv);
        BitmapUtils bitmapUtils = new BitmapUtils(this);
        bitmapUtils.display(iv, url);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值