图片质量压缩的方法

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

        }
        //压缩好后写入文件中
        FileOutputStream fos = new FileOutputStream(filepath);
        fos.write(baos.toByteArray());
        fos.flush();
        fos.close();
        return image;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

你可能感兴趣的:(Android)