android图片压缩

public final class BitmapUtil {

    private BitmapUtil() {
    }

    public static Bitmap loadBitmapWithScale(
            File imageFile,
            int reqWidth,
            int reqHeight) {

        Bitmap ret = null;
        if (imageFile != null && imageFile.exists() && imageFile.canRead()) {
            if (reqWidth >= 0 && reqHeight >= 0) {
                String filePath = imageFile.getAbsolutePath();

                // 1. 第一次采样
                BitmapFactory.Options options = new BitmapFactory.Options();
                // 只获取尺寸
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(filePath, options);

                // 2. 获取图片原始尺寸, 计算采样数值
                options.inSampleSize = calcInSampleSize(options, reqWidth, reqHeight);

                // 3. 再次设置,加载图像到内存
                options.inJustDecodeBounds = false;

                // 4. TODO: 可以使用 inPreferredConfig 来进一步降低图片像素内存
                // 所有的 PNG 图片,都可以支持透明
                // 所有的 JPG 图片,都不支持透明
                String type = options.outMimeType;
                if (type != null) {
                    // 根据 MIME type 来判断图像的文件格式
                    // image/png
                    // image/jpeg
                    if(type.endsWith("png")){
                        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
                    }else if(type.endsWith("jpeg")){
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                    }
                }
                ret = BitmapFactory.decodeFile(filePath, options);
            }
        }
        return ret;
    }

    private static int calcInSampleSize(
            BitmapFactory.Options op,
            int reqWidth,
            int reqHeight) {
        int inSampleSize = 1;
        int outWidth = op.outWidth;
        int outHeight = op.outHeight;

        if(reqWidth > 0 && reqHeight > 0){
            int halfW = outWidth >> 1;
            int halfH = outHeight >> 1;

            while ((halfW / inSampleSize) >= reqWidth
                    && (halfH / inSampleSize) >= reqHeight){
                inSampleSize *= 2;
            }

        }

        return inSampleSize;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值