Android bitmap压缩本地图片

由于G20没地方完去了, 所以在这里写写博客,不写博客的程序员不是好裁缝!很多人会遇到这样的问题,不知道图片如何压缩之后再适配到android中的组件,如imageview等,因为android中产生的oom基本都是图片曹操的,因为系统分配给每个app的内存都是有限而且一定的,所以图片如何处理显得格外重要思密达!!!下来我们就开始撸代码了!*
想要改变图片的大小,基本都是改变bitmapFactory.options的inSampleSize的值, 假如这个是1, 则 图片会被压缩为原图的宽高的1/1(有没有晕, 还这么写), 如果是2, 则是原图的宽高的1/2, 这样图片就变小了, 所以我们的任务很简单, 就是改变inSampleSize, ok, 代码奉上!!!**

public static Bitmap getRightBitmap(String filePath, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //似不似只获取原图的宽高,当然是true了;
        options.inJustDecodeBounds = true;

    //获取
        BitmapFactory.decodeFile(filePath,options);

    //获取改变后的值,并赋值给现在的inSampleSize
        options.inSampleSize = calculte(options, reqWidth, reqHeight);

    //搞完事,擦屁股,有该为false,获取整个位图
        options.inJustDecodeBounds = false;

    //返回压缩后的bitmap
        return BitmapFactory.decodeFile(filePath, options);

    }


    /**
     * get right inSampleSize
     * @param options BitmapFactory
     * @param reqWidth the height wo need
     * @param reqHeight the widht wo need
     * @return int inSampleSize  wo need
     */
    private static int calculte(BitmapFactory.Optionsoptions, int reqWidth, int reqHeight) {
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;

        int inSampleSize = 1;

    if (reqWidth > outHeight || reqHeight > outHeight) {
            int widthRate = Math.round(reqWidth * 1.0f / outWidth);//round四舍五入,因为inSampleSize必须是int类型
            int heightRate = Math.round(reqHeight * 1.0f / outHeight);
        //获取2个值中的最大值,压缩图片当然是要按大的值压缩,记住这里是倒数
            inSampleSize = Math.max(widthRate, heightRate);
        }
        return inSampleSize;

    }
多来一嘴,小的初来乍到,macDown不怎么6,观众老爷先难受难受!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值