图片压缩小例子

来源:互联网 发布:数据库软件access 编辑:程序博客网 时间:2024/04/27 00:24

//图片压缩处理

BitmapFactory.Options option = newBitmapFactory.Options();

option.inSampleSize = 2;//宽高都压缩为原来的二分之一,此参数需要根据图片要展示的大小来确定

option.inPreferredConfig =Bitmap.Config.RGB_565;//设置图片格式,RGB_565这个格式占用内存最小。

Bitmap bitmap =BitmapFactory.decodeStream(inputStream, null, option);



BitmapUtils中计算inSampleSize值的方法:

public static int calculateInSampleSize(BitmapFactory.Options options, int maxWidth, int maxHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (width > maxWidth || height > maxHeight) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) maxHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) maxWidth);
            }

            final float totalPixels = width * height;

            final float maxTotalPixels = maxWidth * maxHeight * 2;

            while (totalPixels / (inSampleSize * inSampleSize) > maxTotalPixels) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }

0 0