Android 图片压缩

最近在做类似QQ空间的功能,在显示图片界面时要进行图片尺寸的压缩,开始以为很难,没想到很简单

自定义一个ImageCompressTool 工具类

//里面有个压缩图片的方法

public static Bitmap compressBySize (Bitmap bitmap, int targetWidth, int targetHeight){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//将bitmap按质量为100的方式压缩到baos中
        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inJustDecodeBounds = true;
        bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, option);
        int imgWidth = option.outWidth;
        int imgHeight = option.outHeight;
        int widthRatio = (int) Math.ceil(imgWidth/(float)targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float)targetHeight);
        if (widthRatio > 1 && heightRatio > 1){//如果目标尺寸小于图片尺寸
            if (widthRatio > heightRatio){
                option.inSampleSize = widthRatio;
            }else {
                option.inSampleSize = heightRatio;
            }
        }
        option.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, option);
        return bitmap;
    }//这就是压缩图片的方法

要压缩图片的地方只需要调一下
  Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
            bitmap = ImageCompressTool.compressBySize(bitmap, 800, 800);//规定宽最大是800, 高也是
            holder.picImage.setImageBitmap(bitmap);

OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值