Android的Bitmap的压缩使用

1.尺寸压缩:
Android Bitmap面面观|杰风居 该链接的Bitmap详情说的很清晰,建议了解一下。 这篇文章说的,使用Bitmap节省内存最重要的技巧就是加载合适大小的缩略图,需要先读取Bitmap的原始大小并且设置inJustDecodeBounds ,按缩小了合适的倍数的大小Bitmap进行加载。

   public static Bitmap decodeSampledBitmapByPath(String path, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

2.质量压缩
该定义转自详解Bitmap尺寸压缩与质量压缩|flowsky37——质量压缩不会改变图片的像素点,即前面我们说到的在转化为bitmap时占用内存变大时状况不会得到改善。但是能方便的设置压缩百分比,达到我们需要的大小。还是先看方法:
Bitmap.compress(CompressFormat format, int quality, OutputStream stream)
简单解释一下这三个参数,第一个表示Bitmap被压缩成的图片格式;第二个表示压缩的质量控制,范围0~100,很好理解。quality为80,表示压缩为原来80%的质量效果。有些格式,例如png,它是无损的,这个值设置了也是无效的。因为质量压缩是在保持像素前提下改变图片的位深及透明度等来压缩图片的。

  public static Bitmap compressBitmap(Bitmap bitmap, int maxkb) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > maxkb && options > 0) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 5;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, null);
        LogUtil.e(TAG, options + "," + baos.toByteArray().length / 1024);
        return bitmap;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值