- 为什么要高效加载
- 由于Bitmap的特殊性以及android对单个应用所施加的内存限制,比如16MB,这就导致加载Bitmap的时候很容易出现内存溢出
- 高效加载四个步骤
- options true
- 获取outHeight outWidh
- 计算采样率
- 加载图片
import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; /** * MyApplication * Created by lzw on 2019/2/28. 15:09:25 * 邮箱:[email protected] * All Rights Saved! Chongqing AnYun Tech co. LTD */ public class BitmapUtil { //如何加载一个Bitmap 四种方法 BitmapFactory decodeResource decodeStream decodefile decodeByteArray public static Bitmap decodeSampledBitmapFromResource(Resources resources,int resId, int reqWidth,int reqHeight){ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//BitmapFactory 只会解析原始图片的宽、高信息,并不会真正地加载图片 BitmapFactory.decodeResource(resources,resId,options); options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);// 2 3步合到一起了 options.inJustDecodeBounds = false;//设置成false才会加载图片 ,切记~~ return BitmapFactory.decodeResource(resources,resId,options); } private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; Log.i("BitmapUtil", "calculateInSampleSize: outHeight"+height+" width="+width); int sampleSize = 1; if (height > reqHeight || width>reqWidth){ final int halfWidth = width/2; final int halfHeight = height/2; while ((halfHeight/sampleSize)>=reqHeight && (halfWidth/sampleSize)>=reqWidth){ sampleSize*=2; } } Log.i("BitmapUtil", "calculateInSampleSize: ="+sampleSize); return sampleSize; } }
Bitmap bitmap = BitmapUtil.decodeSampledBitmapFromResource(getResources(),R.drawable.abc,100,100); int count=bitmap.getAllocationByteCount(); Log.i(TAG, "initView: count="+count); imageView.setImageBitmap(bitmap);