通常我们在开发android应用程序时,在加载图片时常常需要与Bitmap打交道,一般会使用BitmapFactory中提供的相关decode方法获取;
如果一张很大的图片,我们不加处理直接decode的话常常会抛出oom即 out of memory的异常。为了尽量避免这种情况的发生,我们就会用到BitmapFactory中的一个内部类Options提供相关选项进行设置。
inJustDecodeBounds 如果将其设为true的话,在decode时将会返回null,通过此设置可以去查询一个bitmap的属性,比如bitmap的长与宽,而不占用内存大小。
inPreferredConfig 通过设置此值可以用来降低内存消耗,默认为ARGB_8888: 每个像素4字节. 共32位。
Alpha_8: 只保存透明度,共8位,1字节。
ARGB_4444: 共16位,2字节。
RGB_565:共16位,2字节。
如果不需要透明度,可把默认值ARGB_8888改为RGB_565,节约一半内存。
inSampleSize 对大图片进行压缩,可先设置Options.inJustDecodeBounds,获取Bitmap的外围数据,宽和高等。然后计算压缩比例,进行压缩。
inPurgeable与inInputShareable 二个是并列使用,如果设置了inPurgeable = false,则inInputShareable的值会被忽略;这二个选项的作用主要是便于系统及时回收bitmap占用的内存; inPurgeable:设置为True,则使用BitmapFactory创建的Bitmap用于存储Pixel的内存空间,在系统内存不足时可以被回收,当应用需要再次访问该Bitmap的Pixel时,系统会再次调用BitmapFactory 的decode方法重新生成Bitmap的Pixel数组。 设置为False时,表示不能被回收。
inInputShareable:设置是否深拷贝,与inPurgeable结合使用,inPurgeable为false时,该参数无意义
public class MainActivity extends AppCompatActivity {
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.main_iv);
Bitmap bitmap = bitmapZip(getResources(), R.mipmap.bb, 1000, 1000);
Log.i("00000000", "onCreate: " + bitmap.getByteCount());
iv.setImageBitmap(bitmap);
}
public Bitmap bitmapZip(Resources resource, int id, int width, int height) {
BitmapFactory.Options option = new BitmapFactory.Options();
//true直接获取图片信息,而不把图片放在内存中
option.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.mipmap.bb, option);
int width1 = option.outWidth;
int height1 = option.outHeight;
if (width1 > width && height1 > height) {
int scalewidth = width1 / width;
int scaleheigh = height1 / height;
option.inSampleSize = scaleheigh > scalewidth ? scaleheigh : scalewidth;
}
//option.inSampleSize = 4;
option.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bb, option);
return bitmap;
}
}