关于图片压缩

最近项目中用到图片压缩,总结一下,要不时间长忘得快.
看来看去也就两种方法,一种尺寸压缩,一种质量压缩.
先看下代码,尺寸压缩

public static Bitmap resetImgSize(Bitmap bitMap, int size) {
        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 设置想要的大小
//        int newWidth = 200;
//        int newHeight = 200;
        int newWidth = size;
        int newHeight = size;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,
                matrix, true);
        return bitMap;
    }

通过设置的宽度和高度和图片本身的宽高,得到想要比例,然后通过矩阵缩放,创建新图片.
质量压缩

public static Bitmap compressBmpFromBmp(Bitmap image) {
//        BitmapFactory.Options op = new BitmapFactory.Options();
//        op.inPreferredConfig = Bitmap.Config.RGB_565;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        while (baos.toByteArray().length > 1024 * 100 && options > 10) {
            baos.reset();
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }

        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

主要通过bitmap.compress()方法进行压缩,第一个参数格式,第二个压缩比例0–100,100代表不压缩, 第三个参数是一个输出流,其中的数据被写入一个 byte 数组.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值