从图库选择图片,实际是是加载图片到内存,如果图片过大,容易发生OOM异常。如果同一个Activity多次选择图片,及时没有发生OOM异常,也容易出现,当返回Activity时,Activity被重新onCreate了一个,原先的被回收了。我们应该讲图片进行缩放一下在加载到控件上。
// TODO 打开本地图库
Intent intent = new Intent( Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, LOAD_IMAGE);
if (resultCode == RESULT_OK) {
if(requestCode==LOAD_IMAGE){//打开图库
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Intent intent=new Intent(SelectPhotoDialog.this,HonorNewActivity.class);
intent.putExtra("picturePath", picturePath);
setResult(RESULT_OK, intent);
finish();
}
String picturePath=data.getStringExtra("picturePath");
// listBit.add(BitmapFactory.decodeFile(picturePath));
Bitmap bitmap=ImageHelper.loadBitmap(screenWidth, screenHeight, picturePath);
listBit.add(bitmap);
处理图片的方法如下:
//加载大图到内存容易OOM
public static Bitmap loadBitmap(int screenWidth,int screenHeight,String src) {
// 图片解析的配置
Options options = new Options();
// 不去真正解析图片,只是获取图片的宽高
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(src, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
int scaleX = imageWidth / screenWidth;
int scaleY = imageHeight / screenHeight;
int scale = 1;
if (scaleX >= scaleY && scaleX >= 1) {
// 水平方向的缩放比例比竖直方向的缩放比例大,同时图片的宽要比手机屏幕要大,就按水平方向比例缩放
System.out.println("按宽比例缩放");
scale = scaleX;
} else if (scaleY >= scaleX && scaleY >= 1) {
// 竖直方向的缩放比例比水平方向的缩放比例大,同时图片的高要比手机屏幕要大,就按竖直方向比例缩放
System.out.println("按高比例缩放");
scale = scaleY;
}
System.out.println("缩放比例:" + scale);
// 真正解析图片
options.inJustDecodeBounds = false;
// 设置采样率
options.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(src,options);
return bitmap;
}