Android進階之Bitmap的高效加載

一、Bitmap的加載

BitmapFactory提供了四個方法:

  • docodeFiles
  • decodeResource
  • decodeStream
  • decodeByteArray

二、Bitmap的高效加載

採用Bitmap.Options來加載所需尺寸的圖片,主要使用它的inSampleSize參數,當inSampleSize大於1縮放。(inSampleSize會向下去2的指數)
高效加載圖片的流程:

  1. 將BitmapFactory.Options的inJustDecodeBuunds設爲true並加載圖片
  2. 從Bitmap.Options中取出圖片的寬高(outHeight,outWidth)
  3. 結合ImageView的寬高計算採樣率
  4. 將BitmapFatory.Options中的inJustDecodeBounds設爲false並加載圖片
    示例:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView image=findViewById(R.id.image1);
   image.setImageBitmap(sampleDecodeFromResourse(getResources(),R.mipmap.dog,200,200));
    }
    public static Bitmap sampleDecodeFromResourse(Resources res,int resId,int repWidth,int repHeight){
        final BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeResource(res,resId,options);
        options.inSampleSize=computeInSampleSize(options,repWidth,repHeight);
        options.inJustDecodeBounds=false;
        Bitmap bitmap=BitmapFactory.decodeResource(res,resId,options);
        return bitmap;
    }
    public static int computeInSampleSize(BitmapFactory.Options options,int repWidth, int repHeight){
        final int width=options.outWidth;
        final int height=options.outHeight;
        int inSampleSize=1;
        if(width>repWidth||height>repHeight){
            int sampleWidth=((int)width/repWidth)%2==0?width/repWidth+2:width/repWidth+1;
            int sampleHeight=((int)height/repHeight)%2==0?height/repHeight+2:height/repHeight+1;
            inSampleSize=(int)Math.max(sampleWidth,sampleHeight);
        }
        return inSampleSize;
    }
}

三、Android中的緩存策略

常用的緩存算法LRU算法,包括:LruCache和DiskLruCache
LruCache用於內存緩存
DiskLruCache用於存儲設備緩存

(1)LruCache

LruCache是Android提供的一個緩存類,它是一個泛型類,內部採用LinkedHashMap以強引用的方式存儲外界對象。
LruCache典型初始化:

int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
int cacheSize=maxMemory/8;
mMemoryCache=new LruCache<String,Bitmap>(cacheSize){
protected int sizeOf(String key,Bitmap bitmap){
return bitmap.getByteCount();
}
}

添加一個緩存對象

mMemoryCache.put(key,value);

獲取一個緩存對象

mMemory.get(key);

(2)DiskLruCache

DiskLruCache用於設備的存儲,及磁盤緩存。需要添加依賴:

implementation 'com.jakewharton:disklrucache:2.0.2'

DiskLruCache的建立:

Private static final int CACHE_SIZE=1024*1024*50;
File diskCacheDir=getDiskCacheDir(mContext,"bitmap");
if(!diskCacheDir.exists())

首先獲取Url所對應的Key,再根據key通過edit()方法獲取Editor對象,一般key取url的MD5值

private String hashKeyFormUrl(String url){
String hashKey;
try{
final MessageDigest mDigest=MessageDigest.getInstance("MD5");
mDigest.upDtate(url.getByte());
hashKey=bytesToHexString(mDigest.digest());
}catch(NoSuchAlgorithmException e){
hashKey=String.valueOf(url.hashCode());
}
return hashKey;
}
private String bytesToHexString(byte[] bytes){
StringBuffer buffer=new StringBuffer();
for(int i=0;i<bytes.length;i++){
String hex=Integer.toHexString(0xFF&bytes[i]);
if(hex.length==1){
buffer.append('0');
}
buffer.append(hex);
}
return buffer;
}

獲取Editor對象

String key=hashFormUrl(url);
DiskLruCache.Editor editor=mDiskLruCache.edit(key);
if(editor!=null){
OutputStream outputStream=editor.newOutputStream(DISK_CACHE_INDEX);
}

存入緩存對象

public boolean downloadUrlToStream(String url,OutputStream outputStream){
HttpURLConnection connection=null;
BufferedOutputStream out=null;
BufferedInputStream int=null;
try{
final URL url=new URL(url);
connection=(HttpURLConnection)url.openConnection();
in=new BufferedInputStream(connection.getInputStream(),1024*10);
out=new BufferedOutputStream(output,1024*10);
int b;
while((b=in.read())!=-1){
out.write(b);
}
return true;
}catch(IOException e){
e.printStackTrace();
}finally{
if(connection!=null){
connection.disConnection();
}
if(in!=null){
try{
in.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(out!=null){
try{
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}

提交

OutputStream outputStream=editor.newOutputStream(DISK_CACHE_INDEX);
if(downloadUrlToStream(url,outputStream)){
editor.commit();
}else{
editor.abort();
}
mDiskLruCache.flush();

提取

Bitmap bitmp=null;
String key=hashKeyFormUrl(url);
DiskLruCache.Snapshot snapshot=mDiskLruCache.get(key);
if(snapshot!=null){
FileInputStream fileInputStream=(FileInputStream)snapshot.getInputStream(DISK_CACHE_INDEX);
FileDescriptor fileDescriptor=fileInputStream.getFD();//由於使用流解析存在問題,所以採取流對應的文件描述符來解析
bitmap=decodeSampleedBitmapFromFileDescriptor(fileDescriptor,repWidth,repHeight);//自己寫的高效加載圖片的方法和前面的一樣只是解析方法不一樣
if(bitmap!=null){
addBitmapTomemoryCache(key,bitmap);
}
}

最後

如果你看到了這裏,覺得文章寫得不錯就給個讚唄!歡迎大家評論討論!如果你覺得那裏值得改進的,請給我留言。一定會認真查詢,修正不足,定期免費分享技術乾貨。喜歡的小夥伴可以關注一下哦。謝謝!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章