从本地中读取图片,可以用decodeFileDescriptor和decodeFile,至于哪一种方式的耗内存情况作了一次简单对比,可能一次选取6张图片数量过少,貌似区别不大,decodeFileDescriptor能节省1.6mb左右:
1、decodeFileDescriptor的读取6张图片(中间包含压缩、读取、转Base64)
2、decodeFile的读取6张图片(中间包含压缩、读取、转Base64)
public static Bitmap decodeSampledBitmapFromFile(String filepath,int reqWidth,int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; FileInputStream is = null; Bitmap bitmap = null; try { is = new FileInputStream(filepath); BitmapFactory.decodeFileDescriptor(is.getFD(),null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight); options.inJustDecodeBounds = false; try { bitmap = BitmapFactory.decodeFileDescriptor(is.getFD(),null, options); } catch (IOException e) { e.printStackTrace(); }finally { if (is != null) { try { is.close(); } catch (IOException e) { // do nothing here } } } return bitmap; }
public static Bitmap decodeSampledBitmapFromFile2(String filepath,int reqWidth,int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filepath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filepath, options); }
再上50张图片的对比:
decodeFileDescriptor一共用了34mb
decodeFile触发GCC自动回收内存了??
这里再回头看看压缩处理后的代码:
for(int i=0 ; i<mSelectPath.size();i++){ String path = mSelectPath.get(i); //压缩处理(需要提示) Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(path,MyConfig.PicMaxWidth,MyConfig.PicMaxHeight); //保存图片到相应文件夹(质量可能变差) // PictureUtil.saveBitmapWithCompress(bitmap,50,filesList); if(!bitmap.isRecycled() ){ bitmap.recycle(); //回收图片所占的内存 System.gc(); //提醒系统及时回收 } }
通过添加bitmap内存回收和释放:
decodeFileDescriptor的使用情况如下:
这是只使用了16mb