图片的二次采样三级缓存策略

在android开发过程中会经常的加载图片,如果图片过大的话有可能会造成OOM,所以对于图片我们需要做进一步的处理提高性能

首先对图片本身大小入手,即对图片进行二次采样

//实例化Options样式载体
BitmapFactory.Options options = new BitmapFactory.Options();
//将inJustDecodeBounds设置为true,解码的时候可以返回图片的尺寸
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
//图片宽度
int outWidth = options.outWidth;
//图片高度
int outHeight = options.outHeight;
//缩放比例
int sampleSize = 1;
while ((outWidth / sampleSize > destWidth) || (outHeight / sampleSize > destHeight)) {
    sampleSize *= 2;
}
//将inJustDecodeBounds设置为false,返回bitmap
options.inJustDecodeBounds = false;
//设置图片缩放比例 
options.inSampleSize = sampleSize;
//设置色彩模式,默认值是ARGB_8888
options.inPreferredConfig = Bitmap.Config.RGB_565;
//生成采样图片
Bitmap comBitmap = BitmapFactory.decodeFile(filePath, options);

上面是对图片的二次采样过程,下面我们要对图片加载进行三级缓存处理.三级缓存即去图片首先去内存里看是否有该图片,如果没有就查文件里是否有该图片,如果仍然没有我们需要去网络里查该图片.
package demo.liuchen.com.android25_lrucache;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 图片的三级缓存:LruCache--SDCard——Internet
 */
public class MainActivity extends AppCompatActivity {
    private String url = "http://p8.qhimg.com/t0113125382f3c4141a.png";
   // private String url = "http://t2.27270.com/uploads/tu/201606/32/k5xnewfzvz0.jpg";
    private ImageView imageView;
    private LruCache<String,Bitmap> lruCache;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                Bitmap bitmap = (Bitmap) msg.obj;
                imageView.setImageBitmap(bitmap);
            }
        }
    };

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

        imageView = (ImageView) findViewById(R.id.image_Show);
        //获取运行时内存
        Long MaxSize = Runtime.getRuntime().maxMemory();

        //初始化LruCache
        lruCache = new LruCache<String, Bitmap>((int) (MaxSize/8)){
            //key 从内存中取出或存入的对象的名字
            //value 存取的对象
            //return 返回对象的缓存
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };



    }

    public void Click(View view) {
    //当用户需要图片是先到缓存中去取
        Bitmap bitmap = lruCache.get(getName(url));
        if (bitmap!= null){
            imageView.setImageBitmap(bitmap);
        }else {
            //在文件中查找

            Bitmap bitmap1 = getBitmapFromSDCard(getName(url));
            if (bitmap1!= null){
                imageView.setImageBitmap(bitmap1);
                //如果图片在SD卡中找到,将图片放入缓存
                lruCache.put(getName(url),bitmap1);
            }else {

                getBitmapFromNet();
            }
        }


    }
        //从网络获取
    private void getBitmapFromNet() {
        Log.e("TAG","在网络中获取");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL path = new URL(url);
                    HttpURLConnection httpURLConn = (HttpURLConnection) path.openConnection();
                    if (httpURLConn.getResponseCode() == 200){
                        final Bitmap bitmap = BitmapFactory.decodeStream(httpURLConn.getInputStream());
                        //将图片放入缓存中
                        lruCache.put(getName(url),bitmap);
                        //将bitmap存入当前文件的文件中
                        SaveBitmapToSDCard(getName(url),bitmap);
                        Message message = Message.obtain();
                        message.what=1;
                        message.obj=bitmap;


                       handler.sendMessage(message);

                    }

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


            }

        }).start();
    }
//将Bitmap存入sd卡中
    private void SaveBitmapToSDCard(String name, Bitmap bitmap) {
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(new File(getExternalCacheDir(),name)));
            if (name.endsWith("png")||name.endsWith("PNG")){
                //把bitmap存入SdCard中
                bitmap.compress(Bitmap.CompressFormat.PNG,100,bos);
            }else {
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
//从sd卡中获取图片
    private Bitmap getBitmapFromSDCard(String name) {
      //  Log.e("TAG","从SD卡中获取图片");
        Bitmap bitmap = BitmapFactory.decodeFile(getExternalCacheDir().getAbsolutePath()+ File.separator+name);
        //在SD卡中取出的Bitmap进行二次采样,去出去后会将二次采样好的图片放入缓存中
       // Bitmap bitmap = BitmapUtils.getBitmap(getExternalCacheDir().getAbsolutePath()+File.separator+name,100,100);
        return  bitmap;

    }


    //获取Bitmap为Url的名字
    public String getName(String url){
       String name = url.substring(url.lastIndexOf("/")+1,url.length());
        return name;
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值