Android 之 图片压缩

来源:互联网 发布:网络延迟对网速的影响 编辑:程序博客网 时间:2024/05/18 01:49

在上一篇文章中(Android之图片变换)主要说明了bitmap的使用,当然其中也包括一点图片压缩的内容,但是没有详细描述,这篇文章就来阐述一下平时Android使用的图片压缩技术

从图片的压缩方式区分:质量压缩和尺寸压缩。

质量压缩是在保持像素的前提下改变图片的位深及透明度等,来达到压缩图片的目的,经过它压缩的图片文件大小会有改变,但是导入成bitmap后占得内存是不变的。因为要保持像素不变,所以它就无法无限压缩,到达一个值之后就不会继续变小了。显然这个方法并不适用与缩略图,其实也不适用于想通过压缩图片减少内存的适用,仅仅适用于想在保证图片质量的同时减少文件大小的情况而已

尺寸压缩是压缩图片的像素,一张图片所占内存的大小 图片类型*宽*高,通过改变三个值减小图片所占的内存,防止OOM,当然这种方式可能会使图片失真

质量压缩:

public Bitmap compressImage(Bitmap image,int imageSize) {          ByteArrayOutputStream baos = new ByteArrayOutputStream();          image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中          int options = 100;          while ( baos.toByteArray().length / 1024>imageSize) {  //循环判断压缩后图片是否大于100kb,大于继续压缩                     baos.reset();//重置baos即清空baos              image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中              options -= 10;//每次都减少10          }          ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中          Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片          return bitmap;      } 

尺寸压缩:

public void scalePic(int reqWidth,int reqHeight) {        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options);        options.inSampleSize = PhotoUtil.calculateInSampleSize(options, reqWidth,reqHeight);        options.inJustDecodeBounds = false;        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options);        postInvalidate();    }
public static 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) {            final int heightRatio = Math.round((float) height / (float) reqHeight);            final int widthRatio = Math.round((float) width / (float) reqWidth);            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;        }        return inSampleSize;    }

根据具体需求也可以两种压缩方式结合使用

9 0
原创粉丝点击