关于Bitmap 导致的OOM 解决方案

相机越来越好,相片也越来越大, 而手机应用程序所分配的内存有限,  所以在读相片的时候,如果代码写得不好,经常导致OOM. 信息如下:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget 

基本上要注意几个地方:

1 bitmap如果不用了,回收掉

  1. protected void onDestroy()  
  2.         super.onDestroy();  
  3.         if(bmp1 != null){  
  4.             bmp1.recycle();  
  5.             bmp1 null;  
  6.          
  7.         if(bmp2 != null){  
  8.             bmp2.recycle();  
  9.             bmp2 null;  
  10.          
  11.      
protected void onDestroy() {
                super.onDestroy();
                if(bmp1 != null){
                        bmp1.recycle();
                        bmp1 = null;
                }
                if(bmp2 != null){
                        bmp2.recycle();
                        bmp2 = null;
                }
        }

2 先算出该bitmap的大小,然后通过调节采样率的方式来规避

  1. BitmapFactory.Options opts new BitmapFactory.Options();  
  2.         opts.inJustDecodeBounds true;  
  3.         BitmapFactory.decodeFile(imageFile, opts);  
  4.         opts.inSampleSize computeSampleSize(opts, minSideLength, maxNumOfPixels);  
  5.         opts.inJustDecodeBounds false;  
  6.         try  
  7.             return BitmapFactory.decodeFile(imageFile, opts);  
  8.         catch (OutOfMemoryError err)  
  9.          
  10.         return null;  
BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(imageFile, opts);
                opts.inSampleSize = computeSampleSize(opts, minSideLength, maxNumOfPixels);
                opts.inJustDecodeBounds = false;
                try {
                        return BitmapFactory.decodeFile(imageFile, opts);
                } catch (OutOfMemoryError err) {
                }
                return null;

3 在进行文件传输时,最好采用压缩的方式变成byte[]再传输

  1. public static byte[] bitmap2Bytes(Bitmap bm)  
  2.         ByteArrayOutputStream baos new ByteArrayOutputStream();  
  3.         bm.compress(Bitmap.CompressFormat.JPEG, 90, baos);  
  4.         return baos.toByteArray();  
  5.      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值