Android中Bitmap的高效加载

作者: 码农仔 | 来源:发表于2016-07-10 14:01 被阅读666次

    为了避免在ImageView中加载的图片过大而导致程序出现OOM的现象,利用BitmapFactory.Option的有关方法来实现。

    主要流程

    1. 创建BitmapFactorty.Options对象设置inJustDecodeBound属性为true并加载图片
    2. 从BitmapFactory.Options 中取出图片的宽高信息,它们对应于outWidth和outHeight参数。
    3. 根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize。
      4.将BitmapFactory.Options的inJuseDecodeBounds设为false,然后重新加载图片
        /**
         * @return
         * 压缩Bitmap
         */
        private Bitmap compressBitmap() {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getResources(), R.drawable.ic, options);
            options.inSampleSize = calculateInSmapleSize(options, 200, 200);
            options.inJustDecodeBounds = false;
            return  BitmapFactory.decodeResource(getResources(), R.drawable,.ic, options);
        }
    
        /**
         * @param options
         * @param reqWidth
         * @param reqHeight 计算inSmapleSize(采样率)
         */
        private int calculateInSmapleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
            final int width = options.outWidth;
            final int height = options.outHeight;
    
            int inSampleSize = 1;
    
            if (reqWidth < width || reqHeight < height) {
                int halfWidth = width / 2;
                int halfHeigth = height / 2;
    
                while ((halfHeigth / inSampleSize > reqWidth) && (halfWidth / inSampleSize) > reqWidth) {
                    inSampleSize *= 2;
                }
            }
            return inSampleSize;
        }
    

    相关文章

      网友评论

        本文标题:Android中Bitmap的高效加载

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