Android 原生方法更省内存获取bitmap

Bitmap 中 decodeFileDescriptor(),decodeFile()两个方法对比

用decodeFileDescriptor()来生成bimap比decodeFile()省内存

例子
    FileInputStream is = = new FileInputStream(path);  
    bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts); 

替换

    Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);  
    imageView.setImageBitmap(bmp); 
原因

查看BitmapFactory的源码,对比一下两者的实现,可以发现decodeFile()最终是以流的方式生成bitmap

decodeFile源码

  1. decodeFile源码

     public static Bitmap decodeFile(String pathName, Options opts) {  
       Bitmap bm = null;  
        InputStream stream = null;  
         try {  
             stream = new FileInputStream(pathName);  
             bm = decodeStream(stream, null, opts);  
        } catch (Exception e) {  
             /*  do nothing. 
                 If the exception happened on open, bm will be null. 
             */  
         } finally {  
            if (stream != null) {  
                 try {  
                     stream.close();  
                 } catch (IOException e) {  
                     // do nothing here  
                 }  
             }  
         }  
         return bm;  
     }  

查看BitmapFactory的源码,对比一下两者的实现,可以发现decodeFile()最终是以流的方式生成bitmap

  1. decodeFileDescriptor源码

    1.   public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {  
    2.        if (nativeIsSeekable(fd)) {  
    3.            Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);  
    4.            if (bm == null && opts != null && opts.inBitmap != null) {  
    5.                throw new IllegalArgumentException("Problem decoding into existing bitmap");  
    6.            }  
    7.            return finishDecode(bm, outPadding, opts);  
    8.        } else {  
    9.            FileInputStream fis = new FileInputStream(fd);  
    10.            try {  
    11.                return decodeStream(fis, outPadding, opts);  
    12.            } finally {  
    13.                try {  
    14.                    fis.close();  
    15.                } catch (Throwable t) {/* ignore */}  
    16.            }  
    17.        }  
    18.    }  
    19.   
    20. private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,Rect padding, Options opts); 

decodeFileDescriptor的源码,可以找到native本地方法decodeFileDescriptor,通过底层生成bitmap

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值