Bitmap加载的正确方式

1 篇文章 0 订阅
1 篇文章 0 订阅
//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方法

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;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值