Android 图片压缩

来源:互联网 发布:xmind8 mac 激活码 编辑:程序博客网 时间:2024/06/09 15:14

最近在做类似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

原创粉丝点击