解决一个因BitMap引起的OOM问题
Updated:
Contents
BitmapFactory.decodeStream引起了OutOfMemory.
在decodeStream之前,通过设置options.inJustDecodeBounds = true;让Bitmap实现虚加载。
设置options.inJustDecodeBounds = true;让Bitmap实现虚加载。
使用options.outWidth和options.outHeight获取图片宽和高。
再使用ImageLoader.getInstance().displayImage加载图片。
public class PhotoViewFragment extends Fragment {
private PhotoView mGestureImageView;
private Bitmap mBitmap;
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_photo_view_show, container, false);
mGestureImageView = (PhotoView) inflateView.findViewById(R.id.image_turn_show_gestureImageView);
getBundleData();
try {
/*减少内存占用*/
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
opt.inJustDecodeBounds = true;//虚加载
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator + "abc.png");
mBitmap = BitmapFactory.decodeStream(fis, null, opt);
int width = opt.outWidth;
int height = opt.outHeight;
if (height / width >= 1.6) {//判断横竖图
mGestureImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
mGestureImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
DisplayImageOptions op = new DisplayImageOptions.Builder()
.cacheInMemory(true) // default
.build();
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + File.separator + "abc.png"));
ImageLoader.getInstance().displayImage(uri.toString(), mGestureImageView, op);
} catch (Exception e) {
Log.e("Fragment", "onCreateView image-view", e);
}
return inflateView;
}
/**
* 重置GestureImageView为原大小
*/
public void resetGestureImageView() {
mGestureImageView.reset();
}
/**
* 获得Bundle
*/
private void getBundleData() {
Bundle bundle = getArguments();
}
@Override
public void onPause() {
super.onPause();
mGestureImageView.reset();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mBitmap != null && !mBitmap.isRecycled()) {
mBitmap.recycle();
mBitmap = null;
}
}
}