您的位置:首页 > 其它

相册获取图片报OOM异常解决办法

2017-01-13 17:02 351 查看
获取一个图片容易报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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: