Bitmap有效的压缩方式

在Android开发中我们都会遇到在一个100*100的ImageView上显示一张过大的图片,如果直接把这张图片显示上去对我们应用没有一点好处反而存在OOM的危险,所以我们有必要采用一种有效压缩方式来显示上去。

private void calculateBitmapInSimpleSize() {
        Bitmap _bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage);
        getBitmapDatas(_bitmap);

        BitmapFactory.Options optioins = new BitmapFactory.Options();
        optioins.inJustDecodeBounds = true;
//        optioins.inPreferredConfig = Bitmap.Config.RGB_565;//11158560
        optioins.inPreferredConfig = Bitmap.Config.ARGB_8888;//22317120
        BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins);
        int reqWidth = optioins.outWidth;
        int reqHeight = optioins.outHeight;

        Log.w(TAG, "reqWidth = " + reqWidth);
        Log.w(TAG, "reqHeight = " + reqHeight);

        int inSampleSize = 1;
        final int widthRatio = Math.round((float)reqWidth / 100f);
        final int heigthRatio = Math.round((float) reqHeight / 100f);
        // 取最小值 这将保证压缩出来的图片大于或者等于请求的宽度或者高度
        inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio;
        Log.w(TAG, "first inSampleSize = " + inSampleSize);

        final int totalPixel = 100 * 100;
        final int totalReqPixel = reqWidth * reqHeight * 2;

        Log.w(TAG, "totalReqPixel = " + totalReqPixel);

        while (totalPixel / (inSampleSize * inSampleSize) > totalReqPixel) {
            Log.w(TAG, "totalPixel = " + (totalPixel / (inSampleSize * inSampleSize)));
            inSampleSize ++;
        }

        Log.w(TAG, "LastInSampleSize = " + inSampleSize);

        optioins.inJustDecodeBounds = false;

        Bitmap lastBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins);
        getBitmapDatas(lastBitmap);

        mImageView.setImageBitmap(lastBitmap);

    }

通过打印log我们可以清楚发现一张原始的图片占有22317120字节,经过压缩后11158560(RGB_565)/ 22317120(RGB8888)明显所占用的内存都减少了,尽量降低这种情况带来的OOM。
做法:
1.optioins.inJustDecodeBounds = true设置为true可用于读取该bitmap的宽高且不会占用内存。
2.optioins.inPreferredConfig = Bitmap.Config.RGB_565设置在内存中以占用最少的方式,相比RGB_8888只有其一半的内存占有。
3.final int widthRatio = Math.round((float)reqWidth / 100f);
final int heigthRatio = Math.round((float) reqHeight / 100f);
inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio;
计算压缩比例,取最小值 这将保证压缩出来的图片大于或者等于请求的宽度或者高度。
4.在要显示到ImageView的时候optioins.inJustDecodeBounds = false设回false这样就能正常显示了

// 计算bitmap所占内存值
 public void getBitmapDatas(Bitmap bitmap) {
         Log.w(TAG, "Bitmap size = " + bitmap.getByteCount());
    }

采用以上的压缩方式 我们就能避免一张过大的图片”浪费”的显示在ImageView上造成内存消耗过大。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值