您的位置:首页 > 其它

Bitmap加载的正确方式

2015-07-03 16:26 561 查看
[code]//NOTE: 1、得到要压缩的比例(也就是options.inSampleSize)
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置只获取图片的尺寸(宽高以及Mime信息)
        options.inJustDecodeBounds = true;
        //将图片的尺寸信息设置options中
        BitmapFactory.decodeFile(coverImgPath, options);
        //获取将要压缩的比例
        options.inSampleSize = ImageUtils.calculateInSampleSize(options, mIvRaceCoverImg.getWidth(), mIvRaceCoverImg.getHeight());
        //NOTE: 2、根据上面得到的压缩比例,压缩bitmap
        //设置获取图片,而非仅仅获取图片的尺寸
        options.inJustDecodeBounds = false;
        //根据option.inSampleSize解析并压缩图片文件为bitmap
        Bitmap bitmap = BitmapFactory.decodeFile(coverImgPath, options);
        LogCus.d("缩小尺寸后,宽度:" + bitmap.getWidth() + "; 高度:" + bitmap.getHeight());


calculateInSampleSize方法

[code]public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        LogCus.d("height>>" + height + ";width>>>" + width);
        LogCus.d("reqWidth>>" + reqWidth + ";reqHeight>>>" + reqHeight);

        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.
            // 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下,取可能的inSampleSize的最大值
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        LogCus.d("inSampleSize >>>" + inSampleSize);

        return inSampleSize;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: