397_压缩图片到一定大小(质量)

来源:互联网 发布:水写布练字好吗知乎 编辑:程序博客网 时间:2024/06/06 06:26




压缩图片到一定大小(质量)


    public Bitmap compressImage(Bitmap image) {
        
        //创建字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();


        //质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;


        //循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 100) {
            
            //重置baos即清空baos
            baos.reset();
            
            //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差  ,第三个参数:保存压缩后的数据的流
            //这里压缩options%,把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);


            //每次都减少10
            options -= 10;
        }


        //把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());


        //把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        
        return bitmap;
    }



0 0