獲取一個圖片容易報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();
}
}
}