Android虽然会自动管理内存,JAVA也有garbage collection (GC )内存回收机制。

但是如果程序在一次操作中打开几个M的文件,那么通常会出现下面的错误信息。

02-04 21:46:08.703: ERROR/dalvikvm-heap(2429): 1920000-byte external allocation too large for this process.

02-04 21:52:28.463: ERROR/AndroidRuntime(2429): java.lang.OutOfMemoryError: bitmap size exceeds VM budget

移动终端因为内存有限,往往图片处理经常出现上述的错误。

解决方法:

1.明确调用System.gc();

这种内存回收会有一定的作用,但是请不要太期待。

2.图片处理完成后回收内存。

请在调用BitMap进行图片处理后进行内存回收。

bitmap.recycle();

这样会把刚刚用过的图片占用的内存释放。

3.图片处理时指定大小。

下面这个方法处理几个M的图片时是必须的。

BitMap getBitpMap(){
ParcelFileDescriptor pfd;
try{
pfd = mCon.getContentResolver().openFileDescriptor(uri, "r");
}catch (IOException ex){
return null;
}
java.io.FileDescriptor fd = pfd.getFileDescriptor();
BitmapFactory.Options options = new BitmapFactory.Options();
//先指定原始大小
options.inSampleSize = 1;
//只进行大小判断
options.inJustDecodeBounds = true;
//调用此方法得到options得到图片的大小
BitmapFactory.decodeFileDescriptor(fd, null, options);
//我们的目标是在800pixel的画面上显示。
//所以需要调用computeSampleSize得到图片缩放的比例
options.inSampleSize = computeSampleSize(options, 800);
//OK,我们得到了缩放的比例,现在开始正式读入BitMap数据
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;

//根据options参数,减少所需要的内存
Bitmap sourceBitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);
return sourceBitmap;
}
//这个函数会对图片的大小进行判断,并得到合适的缩放比例,比如2即1/2,3即1/3
static int computeSampleSize(BitmapFactory.Options options, int target) {
int w = options.outWidth;
int h = options.outHeight;
int candidateW = w / target;
int candidateH = h / target;
int candidate = Math.max(candidateW, candidateH);
if (candidate == 0)
return 1;
if (candidate > 1) {
if ((w > target) && (w / candidate) < target)
candidate -= 1;
}
if (candidate > 1) {
if ((h > target) && (h / candidate) < target)
candidate -= 1;
}
if (VERBOSE)
Log.v(TAG, "for w/h " + w + "/" + h + " returning " + candidate + "(" + (w/candidate) + " / " + (h/candidate));
return candidate;
}

更多相关文章

  1. 调用Android系统设置
  2. Android性能优化系列---管理你的app内存(一)
  3. Android内存泄漏检测工具使用手册
  4. Android与Js调用
  5. Android-内存映射mmap
  6. NDK(1)--体验NDK
  7. 关于Android(安卓)NDK如何成功调用stl的使用分析
  8. [置顶] 关于Android(安卓)NDK如何成功调用stl的使用分析
  9. android调用系统相机拍摄多张照片

随机推荐

  1. Android 事件流详解之View事件分发
  2. Android深度定制化TabLayout:圆角,渐变色,背
  3. 另一个视角搞android——《Android软件安
  4. 修改android原型button样式
  5. android自学笔记 开始--->第一个应用--->
  6. 设置Listview item 的分隔线
  7. Android(安卓)SQLiteStatement 编译、执
  8. Android(安卓)APK反编译详解(附图)
  9. Android(安卓)代码名字-API级别-版本号-N
  10. android的编译和运行过程深入分析