关于图片压缩

来源:互联网 发布:立体模拟软件 编辑:程序博客网 时间:2024/05/17 02:00

最近项目中用到图片压缩,总结一下,要不时间长忘得快.
看来看去也就两种方法,一种尺寸压缩,一种质量压缩.
先看下代码,尺寸压缩

public static Bitmap resetImgSize(Bitmap bitMap, int size) {        int width = bitMap.getWidth();        int height = bitMap.getHeight();        // 设置想要的大小//        int newWidth = 200;//        int newHeight = 200;        int newWidth = size;        int newHeight = size;        // 计算缩放比例        float scaleWidth = ((float) newWidth) / width;        float scaleHeight = ((float) newHeight) / height;        // 取得想要缩放的matrix参数        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        // 得到新的图片        bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,                matrix, true);        return bitMap;    }

通过设置的宽度和高度和图片本身的宽高,得到想要比例,然后通过矩阵缩放,创建新图片.
质量压缩

public static Bitmap compressBmpFromBmp(Bitmap image) {//        BitmapFactory.Options op = new BitmapFactory.Options();//        op.inPreferredConfig = Bitmap.Config.RGB_565;        ByteArrayOutputStream baos = new ByteArrayOutputStream();        int options = 100;        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);        while (baos.toByteArray().length > 1024 * 100 && options > 10) {            baos.reset();            options -= 10;            image.compress(Bitmap.CompressFormat.JPEG, options, baos);        }        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);        return bitmap;    }

主要通过bitmap.compress()方法进行压缩,第一个参数格式,第二个压缩比例0–100,100代表不压缩, 第三个参数是一个输出流,其中的数据被写入一个 byte 数组.

0 0