android 图片压缩方法分析与学习

bitmap compress 是官方给出的图片质量压缩,通过试验学习了这个压缩的特性如下:

  1. 它是图片质量压缩,不会改变图片的分辨率

  2. bitmap.compress(Bitmap.CompressFormat.JPEG, option, bos);

    三个参数说明,1.图片压缩后的格式 2.图片压缩比例 3.压缩后得到的数据

  3. 这个方法会使图片压缩但是,由于是质量压缩,bitmap不会变小,也就是内存依然大,压缩的数据确实变小使用的时候得注意了内存溢出问题

测试方法如下:

 System.out.println("bitmap=="+bitmap.getByteCount());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//通过这里改变压缩类型,其有不同的结果
int option = 100;
while (option > 0)
{
    bitmap.compress(Bitmap.CompressFormat.JPEG, option, bos);
    System.out.println("bos=====" + bos.size());
    option-=10;
    bos.reset();
}

System.out.println("bitmap==" + bitmap.getByteCount());
bitmap.recycle();

ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
System.out.println("bis====="+bis.available());
bitmap = BitmapFactory.decodeStream(bis);
System.out.println("bitmap=="+bitmap.getByteCount());
imageView.setImageBitmap(bitmap);

如果确实要节约内存

就是用如下方法:

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 );


你可能感兴趣的:(android 图片压缩方法分析与学习)