一直使用的图片压缩的代码,做个笔记

废话不多说,直接贴代码,主要目的是做个笔记!很感谢提供这段代码的小伙伴,虽然忘记是从哪个网站上找到的了,真的很实用!

 public void commit() {
        // TODO: 2016/5/23 0023 压缩图片 
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(pics.get(i), options);
            int height = options.outHeight;
            int width = options.outWidth;
            int reqHeight = 0;
            int reqWidth = 480;
            reqHeight = (reqWidth * height) / width;
            // 在内存中创建bitmap对象,这个对象按照缩放大小创建的
            options.inSampleSize = calculateInSampleSize(
                    options, 480, reqHeight);
            options.inJustDecodeBounds = false;
            Bitmap bm = BitmapFactory.decodeFile(
                    pics.get(i), options);
            bm = compressImage(Bitmap.createScaledBitmap(
                    bm, 480, reqHeight, false));
            bitmaps.add(bm);
    }
    // 压缩
    private Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        int options = 100;
        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 100) { 
            options -= 10;// 每次都减少10
            baos.reset();// 重置baos即清空baos
            // 这里压缩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;
    }
     // 计算缩放大小
    private int calculateInSampleSize(BitmapFactory.Options options,
                                      int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

猜你喜欢

转载自blog.csdn.net/baisemaque/article/details/51593496