图片有各种形状和大小。在很多情况下这些图片是远远大于我们的用户界面(UI)且占领着极大的内存空间,假设我们不正确位图进行压缩处理,我们的程序会发生内存泄露的错误。
MainActivity的代码
package com.example.g08_bitmap; import android.os.Bundle;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView; public class MainActivity extends Activity {
private ImageView imageView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.imageView1);
imageView.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.a, 300, 300));
} public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
//先将inJustDecodeBounds属性设置为true,解码避免内存分配
options.inJustDecodeBounds = true;
// 将图片传入选择器中
BitmapFactory.decodeResource(res, resId, options);
// 对图片进行指定比例的压缩
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
//待图片处理完毕后再进行内存的分配,避免内存泄露的发生
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
} // 计算图片的压缩比例
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择长宽高较小的比例,成为压缩比例
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
} }