图片压缩处理方法

来源:互联网 发布:成都多益网络公司地址 编辑:程序博客网 时间:2024/05/17 03:16
    /**     * 图片压缩处理(质量法)     *      * @param image     * @return     */    private 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 > 20) {            // 重置baos即清空baos            baos.reset();            // 每次都减少10            options -= 10;            // 这里压缩options%,把压缩后的数据存放到baos中            image.compress(Bitmap.CompressFormat.JPEG, options, baos);        }        // 把压缩后的数据baos存放到ByteArrayInputStream中        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());        // 把ByteArrayInputStream数据生成图片        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);        return bitmap;    }    /**     * 图片压缩处理(尺寸法)     *      */    public Bitmap resizeBitmap(int width, int height, Bitmap bitmap) {        // 图片尺寸        int bitmapWidth = bitmap.getWidth();        int bitmapHeight = bitmap.getHeight();        // 缩放图片的尺寸        float scaleWidth = (float) width / bitmapWidth;        float scaleHeight = (float) height / bitmapHeight;        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        // 产生缩放后的Bitmap对象        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth,                bitmapHeight, matrix, false);        return resizeBitmap;    }
0 0
原创粉丝点击