Android图片压缩

比较简单,直接上代码

    public static Bitmap compressImage(Bitmap bitmap) {
        if (bitmap != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, baos);
            int length = baos.size();
            Logger.d("compressImage", "before compress  size:" + (length/1024) + "KB");
            final int MIN_BYTE = 200 * 1024;
            //小于200K就放过它吧
            if (length > MIN_BYTE) {
                Logger.d("compressImage", "large than 200KB begin compress.");
                //压缩比例公式,可自行定义
                int quality = (int) (((length - MIN_BYTE) / 5.0 + MIN_BYTE) * 100 / length);
                Logger.d("compressImage", "compress rate:" + quality + "%");
                baos.reset();
                if (bitmap.compress(CompressFormat.JPEG, quality, baos)) {
                    byte[] bs = baos.toByteArray();
                    length = bs.length;
                    Logger.d("compressImage", "compress success new size:" + (length/1024) + "KB");
                    ByteArrayInputStream bais = new ByteArrayInputStream(
                            bs);
                    return BitmapFactory.decodeStream(bais);
                }
            } else {
                Logger.d("compressImage", "Not compress less than 200K size:" + (length/1024) + "KB");
            }
        } else {
            Logger.d("compressImage", "decode bitmap error");
        }
        return bitmap;
    }

 

你可能感兴趣的:(android)