Android_Bitmap压缩杂谈

情况一:图片太大,因为手机资源的稀缺,如果每个图片都很大,很容易出现OOM的情况。所以,适当对图片的质量进行压缩还是有必要的。

实习代码如下:

private Bitmap compressImage(Bitmap image) {  
  
        ByteArrayOutputStream target_baos= new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 100, target_baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中  
        int options = 100;  
        while ( target_baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            target_baos.reset();//重置baos即清空baos  
            image.compress(Bitmap.CompressFormat.JPEG, options, target_baos);//这里压缩options%,把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(target_baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
        return bitmap;  
    }  
 

通过如上方法可以将Bitmap大小进行压缩,有利于APP的内存利用。


情况二:图片尺寸过大,将Bitmap缩放适当尺寸,已完成不同屏幕的适配。

方法1:利用矩阵缩放,代码如下:

        //获取屏幕的宽高
        DisplayMetrics metrics = new DisplayMetrics();
        ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        //标准尺寸屏幕的比例关系,计算出该屏幕下图片的尺寸,并设置一个最大值,放置在另类手机适配出现问题。
        int cellWidth = (int)((180.0f/1080.0f)*width);
        if (cellWidth >240)
            cellWidth = 240;
        int bitmapWidth = getBitmapFor(R.mipmap.pointer_pw).getWidth();
        int bitmapHeight = getBitmapFor(R.mipmap.pointer_pw).getHeight();
        float scale = (float)cellWidth/(float)bitmapWidth;//根据目标尺寸和原始图片尺寸计算比例
        Matrix matrix = new Matrix();
        matrix.postScale(scale,scale);

        // 得出最后的bitmap
        mBitmapBtnDefault = Bitmap.createBitmap(getBitmapFor(R.mipmap.pointer_pw),0,0,bitmapWidth,bitmapHeight,matrix,true);

方法2:利用BitmapFactory.Options 完成缩放

private Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片,此时把options.inJustDecodeBounds 设回true了  
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空  

        newOpts.inJustDecodeBounds = false;
        int factor = 4;
        newOpts.inSampleSize = factor;//设置缩放比例,实际为所设值得倒数
        //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return  bitmap;//压缩好比例大小后再进行质量压缩  
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值