Training图像篇之一:Loading Large Bitmaps Efficiently

来源:互联网 发布:makah5页面制作软件 编辑:程序博客网 时间:2024/06/10 01:55



大多数情况下,从相机得到的图片的实际大小要比我们需要显示的图片尺寸大很多。所以为了节约内存以及提升效率,我们只需要加载与UI组件大小相匹配的低分辨率的图片即可。

1.Read Bitmap Dimensions and Type(读取位图的尺寸与类型)

可以通过设置 option.inJustDecodeBounds=true 来预先读取到图片的尺寸还有类型。从而避免BitmapFactory在构造位图的时候过多的分配内存造成OOM.

BitmapFactory.Options options =newBitmapFactory.Options();
options
.inJustDecodeBounds =true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

2.Load a Scaled Down Version into Memory(加载一个按比例缩小的版本到内存中)

可以通过设置BitmapFactory.Options 中 inSampleSize 的来得到等比例缩小的图片。
比如一张1000x2000的图片,设置 inSampleSize=4,inJustDecodeBounds 为 false后decode得到的图片为250x500。

那如何得 inSampleSize 的值呢? 可以通过1.中返回的 option 及UI组件的大小去计算。

publicstaticint calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){        
   
// Raw height and width of image
   
finalint height = options.outHeight;
   
finalint width = options.outWidth;
   
int inSampleSize =1;

   
if(height > reqHeight || width > reqWidth){

       
finalint halfHeight = height /2;
       
finalint halfWidth = width /2;

       
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
       
// height and width larger than the requested height and width.
       
while((halfHeight / inSampleSize)>= reqHeight
               
&&(halfWidth / inSampleSize)>= reqWidth){
            inSampleSize
*=2;
       
}
   
}

得到 inSampleSize 的值并设置 inJustDecodeBounds 为 false,之后重新调用相关的解码方法就可以得到等比例的缩略图了。代码如下:

publicstaticBitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight){

   
// First decode with inJustDecodeBounds=true to check dimensions
   
finalBitmapFactory.Options options =newBitmapFactory.Options();
    options
.inJustDecodeBounds =true;
   
BitmapFactory.decodeResource(res, resId, options);

   
// Calculate inSampleSize
    options
.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

   
// Decode bitmap with inSampleSize set
    options
.inJustDecodeBounds =false;
   
returnBitmapFactory.decodeResource(res, resId, options);
}

mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.myimage,100,100));

这样,我们通过这个方法去加载任意大小的图片,都可以解决100x100的缩略图了,从而减少OOM的可能。


Training:https://developer.android.com/training/displaying-bitmaps/load-bitmap.html

转载请注明出处:http://blog.csdn.net/fzw_faith/article/details/52295015

0 0
原创粉丝点击