Android学习笔记:关于图片压缩的总结

图片需要压缩的情况大致分为以下两种:
1.将图片保存到本地时进行压缩,即从Bitmap形式到File形式进行压缩。(应用场景:图片上传服务器端)
特点是:当图片从Bitmap到File格式后,File的大小确实被压缩,但是当你重新读取压缩的File文件为Bitmap后,它占的内存并没有改变。
/**

  • 质量压缩

  • @param bmp

  • @param file
    /
    public static void compressBmpToFile(Bitmap bmp, File file) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int options = 80;
    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    while (baos.toByteArray().length / 1024 > 150) {
    baos.reset();
    options -= 10;
    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    }
    try {
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baos.toByteArray());
    fos.flush();
    fos.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    方法说明:该方法是压缩图片的质量,但并不会减少图片的像素。例如:原来600Kb大小的图片,像素是960
    1280,经过该方法压缩后的File形式是在100Kb以下,以方便上传服务器端,但是BitmapFactory.decodeFile到内存中,变成Bitmap时,它的像素还是9601280,计算图片像素的方法是bitmap.getWidthbitmap.getHeight,图片是由像素组成的,每个像素又包含了色素、透明度和饱和度。
    官方文档解释说,它会让图片重新构造,但是图像的位深(即色深)和每个像素的透明度会变化,也就是说jpep格式压缩后,原来图片中透明的元素将消失,所以这种格式很肯能造成图片的失真
    既然它改变了图片的显示质量,达到了对File形式图片的压缩。图片的像素没有变化的话,那重新读取经过压缩的File文件为Bitmap时,它占用的内存并不会少。
    因为:bitmap.getByeCount()是计算它的像素所占用的内存,官方文档解释: Returns the minimum number of bytes that can be used to store this bitmap's pixels.
    2.将图片从本地读到内存,进行压缩,即图片从File格式变为Bitmap形式(应用场景:ImageView显示图片过大容易导致OOM的时候)
    特点:通过设置采样率,减少图片的像素(也就是宽高),达到对内存的Bitmap进行压缩
    private Bitmap compressImageFromFile(String srcPath) {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true;//只读边,不读内容
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

     newOpts.inJustDecodeBounds = false;
     int w = newOpts.outWidth;
     int h = newOpts.outHeight;
     float hh = 800f;// 
      float ww = 480f;// 
      int be = 1;
     if (w > h && w > ww) {
         be = (int) (newOpts.outWidth / ww);
     } else if (w < h && h > hh) {
         be = (int) (newOpts.outHeight / hh);
     }
     if (be <= 0)
         be = 1;
     newOpts.inSampleSize = be;//设置采样率 
    
     newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设 
      newOpts.inPurgeable = true;// 同时设置才会有效 
      newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收 
    
     bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
    

// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
//其实是无效的,大家尽管尝试
return bitmap;
}

方法说明:该方法是对Bitmap格式的图片进行压缩,也就是通过设置采样率,减少Bitmap的像素, 从而减少了它所占的内存。
注意:在压缩好要保存图片的时候,如果对图片的透明度没有要求的话,图片的格式最好保存成.jpg,如果保存成png的话,将会多耗费很长的时间。

你可能感兴趣的:(Android学习笔记:关于图片压缩的总结)