获取一个图片容易报OOM异常,这里做个笔记,但是这个会把图片搞得很模糊,图片的质量有所下降,后续会完善
private void setPic(ImageView imageView, Uri uri) {
if (getActivity() != null) {
//获取目标控件的大小
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
try {
//inJustDecodeBounds为true,可以加载源图片的尺寸大小,decodeStream方法返回的bitmap为null
bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, bmOptions);
// 得到源图片的尺寸
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
//通过比较获取较小的缩放比列
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// 将inJustDecodeBounds置为false,设置bitmap的缩放比列
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
//再次decode获取bitmap
Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, bmOptions);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}