美文网首页
加载图片内存优化的总结

加载图片内存优化的总结

作者: ahking17 | 来源:发表于2017-02-10 19:11 被阅读182次

    使用BitmapRegionDecoder分区域加载图片

    图片加载有一种这样的情况,就是单个图片非常巨大,并且还不允许压缩。比如显示:世界地图、微博长图等。首先不压缩,按照原图尺寸加载,那么屏幕肯定是不够大的,并且考虑到内存的情况,不可能一次性整图加载到内存中,所以肯定是局部加载。这就需要用到Api提供的这个类:BitmapRegionDecoder。

    BitmapRegionDecoder用于显示图片的某一块矩形区域

    使用方法:

    InputStream inputStream = getAssets().open("tangyan.jpg");
    
    //设置显示图片的中心区域
    BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
    mImageView.setImageBitmap(bitmap);
    
    

    有一个显示世界地图的开源项目, https://github.com/johnnylambada/WorldMap
    就是使用BitmapRegionDecoder加载一张96MB的图片.

    The map itself is quite large (6480,3888), so it's way too big to fit in memory all at once (6480 x 3888 x 32 / 8) = 100,776,960 -- over 96 megs.
    The VM heap size Android supports is eith 16 or 24 megs, so we can't fit the whole thing in memory at once.
    
    So WorldMap uses the BitmapRegionDecoder API (available as of API 10) to decode just what it needs to display.
    
    使用Glide优化对内存的占用

    Google介绍了一个开源的加载bitmap的库:Glide,这里面包含了各种对bitmap的优化技巧。

    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap1 = BitmapFactory.decodeResource(Global.mContext.getResources(), R.drawable.splash_default);
    JLog.i("bitmap1 byte = "+bitmap1.getByteCount());
    

    logcat:

    com.qihoo.browser I/ahking: [ (BottomBarManager.java:1322)#HandlePopupMenuAction ] bitmap1 byte = 3686400
    

    splash_default.png, 长720, 宽1280, 占用内存的计算公式
    bitmap = 长720 * 宽1280 * 4(如果是ARGB8888格式的话) = 3,686,400
    正好符合预期.

    Glide的使用方法

    build.grade:

    dependencies {
        compile 'com.github.bumptech.glide:glide:+'
    }
    

    +表示使用最新版本的glide.

    java code:

    Bitmap bitmap2 = Glide.with(MainActivity.this).load(R.drawable.splash_default).asBitmap().into(-1,-1).get();
    int glideByteCount = bitmap2.getByteCount();
    JLog.i("glideByteCount = "+glideByteCount);
    

    log:

    com.github.strictanr I/ahking: [ (MainActivity.java:124)#Run ] glideByteCount = 1843200
    

    使用glide的话, 只占了1.8M的内存, 对内存的占用优化了大概50%.

    glide 实现优化的手段

    主要是使用了inBitmap属性
    http://hukai.me/android-performance-patterns-season-2/

    glide 支持gif动画

    项目中, 与其引入https://github.com/koral--/android-gif-drawable, 为了支持gif动画, 不如直接引入glide去支持gif, 还能同时优化加载png/jpg的内存占用.

    --------DONE.----------

    相关文章

      网友评论

          本文标题:加载图片内存优化的总结

          本文链接:https://www.haomeiwen.com/subject/fzqnittx.html