bitmap.compress(图片压缩的两种方式)(1,质量压缩;2,采样率压缩)

代码如下

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
  int options = 100 ;
  while ( baos.toByteArray().length / 1024 > 32 ) {
  baos.reset();
  image.compress(Bitmap.CompressFormat.JPEG, options, baos);
  options -= 10 ;
  }
  ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
  Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , null );
  最开始使用这个来进行压缩,但是始终压缩不到32k这么小。后来看高手的解释才明白,这种压缩方法之所以称之为质量压缩,是因为它不会减少图片的像素。它是在保持像素的前提下改变图片的位深及透明度等,来达到压缩图片的目的。进过它压缩的图片文件大小会有改变,但是导入成bitmap后占得内存是不变的。因为要保持像素不变,所以它就无法无限压缩,到达一个值之后就不会继续变小了。显然这个方法并不适用与缩略图,其实也不适用于想通过压缩图片减少内存的适用,仅仅适用于想在保证图片质量的同时减少文件大小的情况而已。
  2、采样率压缩法:

  代码如下

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.JPEG, 100, out);
  BitmapFactory.Options newOpts = new BitmapFactory.Options();
  int be = 2;
  newOpts.inSampleSize = be;
  ByteArrayInputStream isBm = new ByteArrayInputStream(out.toByteArray());
  Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , null );
  第二个使用的是这个方法,可以将图片压缩到足够小,但是也有一些问题。因为采样率是整数,所以不能很好的保证图片的质量。如我们需要的是在2和3采样率之间,用2的话图片就大了一点,但是用3的话图片质量就会有很明显的下降。这样也无法完全满足我的需要。不过这个方法的好处是大大的缩小了内存的使用,在读存储器上的图片时,如果不需要高清的效果,可以先只读取图片的边,通过宽和高设定好取样率后再加载图片,这样就不会过多的占用内存。如下

  BitmapFactory.Options newOpts = new BitmapFactory.Options();
  newOpts.inJustDecodeBounds = true ;
  Bitmap bitmap = BitmapFactory.decodeFile(path,newOpts);
  newOpts.inJustDecodeBounds = false ;
  int w = newOpts.outWidth;
  int h = newOpts.outHeight;
  //计算出取样率
  newOpts.inSampleSize = be;
  bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
  这样的好处是不会先将大图片读入内存,大大减少了内存的使用,也不必考虑将大图片读入内存后的释放事宜。

你可能感兴趣的:(图片压缩,android图片压缩)