关于Bitmap中加载图片,防止OOM

   public Bitmap decodeSampledBitmapFromResource(int bitmapResourceId, int reqWidth, int reqHeight) {
        // 设置inJustDecodeBounds = true ,表示先不加载图片
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(file.getPath(), options);
        BitmapFactory.decodeResource(getResources(), bitmapResourceId, options);

        // 调用方法计算合适的 inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // inJustDecodeBounds 置为 false 真正开始加载图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(getResources(), bitmapResourceId, options);
    }

    // 计算 BitmapFactpry 的 inSimpleSize的值的方法
    public int calculateInSampleSize(BitmapFactory.Options options,
                                     int reqWidth, int reqHeight) {
        if (reqWidth == 0 || reqHeight == 0) {
            return 1;
        }

        // 获取图片原生的宽和高
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        // 如果原生的宽高大于请求的宽高,那么将原生的宽和高都置为原来的一半
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // 主要计算逻辑
            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

<h3>关于图片的缩放</h3>

inputBitmap = Bitmap.createScaledBitmap(inputBitmap, inputSpaceWidth, inputSpaceHeight, true);

Bitmap.createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter);
<b>src:</b> The source bitmap.
<b>dstWidth</b> The new bitmap's desired width.
<b>dstHeight</b> The new bitmap's desired height.
<b>filter</b> true if the source should be filtered.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,280评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,761评论 0 17
  • //通过获得资源文件进行设置。根据不同的情况R.color.red也可以是R.string.red或者R.draw...
    gogoingmonkey阅读 1,999评论 0 2
  • □文/从前慢 01 和大多数“富二代”一样,林强自小就生活在蜜罐里,加上爷爷奶奶、爸爸妈妈的多加宠爱,更是助推了他...
    从前慢者阅读 250评论 4 9
  • 对于《穷爸爸富爸爸》这本书来说,我个人相较与别人来说可能会更加亲切。在我小时候我的生命中也有两个爸爸,我的爸爸和舅...
    answersky阅读 227评论 1 2