Android 图片质量压缩,真正的按体积大小进行压缩

百度到的方法,经过测试,我只想说,写法简直是屎!!!!!!!!!!

正确方法:

/**
     * 压缩图片
     *
     * @param image
     * @return
     */
    public static byte[] compressImage(int maxSize, Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        int options = 90;
        byte[] bytes = baos.toByteArray().clone();
        Bitmap temp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        int size = bytes.length;
        while (size / 1024 > maxSize) {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            temp.compress(Bitmap.CompressFormat.JPEG, options, bao);

            byte[] buf = bao.toByteArray().clone();
            size = buf.length;
            Bitmap bitmap = BitmapFactory.decodeByteArray(buf, 0, buf.length);
            options -= 5;
            if (options <= 0) options = 90;
            temp = bitmap;
            bytes = buf.clone();
        }
        return bytes;
    }

你可能感兴趣的:(Android基础)