当前位置: 移动技术网 > 移动技术>移动开发>Android > Android图片压缩(质量压缩和尺寸压缩)

Android图片压缩(质量压缩和尺寸压缩)

2019年07月24日  | 移动技术网移动技术  | 我要评论

在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可用于上传大图前的处理,这样就可以节省一定的流量,毕竟现在的手机拍照都能达到3m左右了,尺寸压缩一般可用于生成缩略图。

两种方法都实装在了我的项目中,结果却发现在质量压缩的模块中,本来1.9m的图片压缩后反而变成3m多了,很是奇怪,再做了进一步调查终于知道原因了。下面这个博客说的比较清晰:

android图片压缩总结

总 结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap,所谓的质量压缩,它其实只能实现对 file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但 是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小 了;

而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;

最后把自己总结的工具类贴出来:

import javaiobytearrayinputstream; 
import javaiobytearrayoutputstream; 
import javaiofile; 
import javaiofilenotfoundexception; 
import javaiofileoutputstream; 
import javaioioexception; 
 
import androidgraphicsbitmap; 
import androidgraphicsbitmapconfig; 
import androidgraphicsbitmapfactory; 
 
/** 
 * image compress factory class 
 * 
 * @author 
 * 
 */ 
public class imagefactory { 
 
  /** 
   * get bitmap from specified image path 
   * 
   * @param imgpath 
   * @return 
   */ 
  public bitmap getbitmap(string imgpath) { 
    // get bitmap through image path 
    bitmapfactoryoptions newopts = new bitmapfactoryoptions(); 
    newoptsinjustdecodebounds = false; 
    newoptsinpurgeable = true; 
    newoptsininputshareable = true; 
    // do not compress 
    newoptsinsamplesize = 1; 
    newoptsinpreferredconfig = configrgb_565; 
    return bitmapfactorydecodefile(imgpath, newopts); 
  } 
   
  /** 
   * store bitmap into specified image path 
   * 
   * @param bitmap 
   * @param outpath 
   * @throws filenotfoundexception 
   */ 
  public void storeimage(bitmap bitmap, string outpath) throws filenotfoundexception { 
    fileoutputstream os = new fileoutputstream(outpath); 
    bitmapcompress(bitmapcompressformatjpeg, 100, os); 
  } 
   
  /** 
   * compress image by pixel, this will modify image width/height 
   * used to get thumbnail 
   * 
   * @param imgpath image path 
   * @param pixelw target pixel of width 
   * @param pixelh target pixel of height 
   * @return 
   */ 
  public bitmap ratio(string imgpath, float pixelw, float pixelh) { 
    bitmapfactoryoptions newopts = new bitmapfactoryoptions();  
    // 开始读入图片,此时把optionsinjustdecodebounds 设回true,即只读边不读内容 
    newoptsinjustdecodebounds = true; 
    newoptsinpreferredconfig = configrgb_565; 
    // get bitmap info, but notice that bitmap is null now  
    bitmap bitmap = bitmapfactorydecodefile(imgpath,newopts); 
      
    newoptsinjustdecodebounds = false;  
    int w = newoptsoutwidth;  
    int h = newoptsoutheight;  
    // 想要缩放的目标尺寸 
    float hh = pixelh;// 设置高度为240f时,可以明显看到图片缩小了 
    float ww = pixelw;// 设置宽度为120f,可以明显看到图片缩小了 
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
    int be = 1;//be=1表示不缩放  
    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
      be = (int) (newoptsoutwidth / ww);  
    } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
      be = (int) (newoptsoutheight / hh);  
    }  
    if (be <= 0) be = 1;  
    newoptsinsamplesize = be;//设置缩放比例 
    // 开始压缩图片,注意此时已经把optionsinjustdecodebounds 设回false了 
    bitmap = bitmapfactorydecodefile(imgpath, newopts); 
    // 压缩好比例大小后再进行质量压缩 
//    return compress(bitmap, maxsize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 
    return bitmap; 
  } 
   
  /** 
   * compress image by size, this will modify image width/height 
   * used to get thumbnail 
   * 
   * @param image 
   * @param pixelw target pixel of width 
   * @param pixelh target pixel of height 
   * @return 
   */ 
  public bitmap ratio(bitmap image, float pixelw, float pixelh) { 
    bytearrayoutputstream os = new bytearrayoutputstream(); 
    imagecompress(bitmapcompressformatjpeg, 100, os); 
    if( ostobytearray()length / 1024>1024) {//判断如果图片大于1m,进行压缩避免在生成图片(bitmapfactorydecodestream)时溢出   
      osreset();//重置baos即清空baos  
      imagecompress(bitmapcompressformatjpeg, 50, os);//这里压缩50%,把压缩后的数据存放到baos中  
    }  
    bytearrayinputstream is = new bytearrayinputstream(ostobytearray());  
    bitmapfactoryoptions newopts = new bitmapfactoryoptions();  
    //开始读入图片,此时把optionsinjustdecodebounds 设回true了  
    newoptsinjustdecodebounds = true; 
    newoptsinpreferredconfig = configrgb_565; 
    bitmap bitmap = bitmapfactorydecodestream(is, null, newopts);  
    newoptsinjustdecodebounds = false;  
    int w = newoptsoutwidth;  
    int h = newoptsoutheight;  
    float hh = pixelh;// 设置高度为240f时,可以明显看到图片缩小了 
    float ww = pixelw;// 设置宽度为120f,可以明显看到图片缩小了 
    //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
    int be = 1;//be=1表示不缩放  
    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
      be = (int) (newoptsoutwidth / ww);  
    } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
      be = (int) (newoptsoutheight / hh);  
    }  
    if (be <= 0) be = 1;  
    newoptsinsamplesize = be;//设置缩放比例  
    //重新读入图片,注意此时已经把optionsinjustdecodebounds 设回false了  
    is = new bytearrayinputstream(ostobytearray());  
    bitmap = bitmapfactorydecodestream(is, null, newopts); 
    //压缩好比例大小后再进行质量压缩 
//   return compress(bitmap, maxsize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 
    return bitmap; 
  } 
   
  /** 
   * compress by quality, and generate image to the path specified 
   * 
   * @param image 
   * @param outpath 
   * @param maxsize target will be compressed to be smaller than this size(kb) 
   * @throws ioexception 
   */ 
  public void compressandgenimage(bitmap image, string outpath, int maxsize) throws ioexception { 
    bytearrayoutputstream os = new bytearrayoutputstream(); 
    // scale 
    int options = 100; 
    // store the bitmap into output stream(no compress) 
    imagecompress(bitmapcompressformatjpeg, options, os);  
    // compress by loop 
    while ( ostobytearray()length / 1024 > maxsize) { 
      // clean up os 
      osreset(); 
      // interval 10 
      options -= 10; 
      imagecompress(bitmapcompressformatjpeg, options, os); 
    } 
     
    // generate compressed image file 
    fileoutputstream fos = new fileoutputstream(outpath);  
    foswrite(ostobytearray());  
    fosflush();  
    fosclose();  
  } 
   
  /** 
   * compress by quality, and generate image to the path specified 
   * 
   * @param imgpath 
   * @param outpath 
   * @param maxsize target will be compressed to be smaller than this size(kb) 
   * @param needsdelete whether delete original file after compress 
   * @throws ioexception 
   */ 
  public void compressandgenimage(string imgpath, string outpath, int maxsize, boolean needsdelete) throws ioexception { 
    compressandgenimage(getbitmap(imgpath), outpath, maxsize); 
     
    // delete original file 
    if (needsdelete) { 
      file file = new file (imgpath); 
      if (fileexists()) { 
        filedelete(); 
      } 
    } 
  } 
   
  /** 
   * ratio and generate thumb to the path specified 
   * 
   * @param image 
   * @param outpath 
   * @param pixelw target pixel of width 
   * @param pixelh target pixel of height 
   * @throws filenotfoundexception 
   */ 
  public void ratioandgenthumb(bitmap image, string outpath, float pixelw, float pixelh) throws filenotfoundexception { 
    bitmap bitmap = ratio(image, pixelw, pixelh); 
    storeimage( bitmap, outpath); 
  } 
   
  /** 
   * ratio and generate thumb to the path specified 
   * 
   * @param image 
   * @param outpath 
   * @param pixelw target pixel of width 
   * @param pixelh target pixel of height 
   * @param needsdelete whether delete original file after compress 
   * @throws filenotfoundexception 
   */ 
  public void ratioandgenthumb(string imgpath, string outpath, float pixelw, float pixelh, boolean needsdelete) throws filenotfoundexception { 
    bitmap bitmap = ratio(imgpath, pixelw, pixelh); 
    storeimage( bitmap, outpath); 
     
    // delete original file 
        if (needsdelete) { 
          file file = new file (imgpath); 
          if (fileexists()) { 
            filedelete(); 
          } 
        } 
  } 
   
} 

android图片压缩总结

一.图片的存在形式

1.文件形式(即以二进制形式存在于硬盘上)

2.流的形式(即以二进制形式存在于内存中)

3.bitmap形式

这三种形式的区别: 文件形式和流的形式对图片体积大小并没有影响,也就是说,如果你手机sd卡上的如果是100k,那 么通过流的形式读到内存中,也一定是占100k的内存,注意是流的形式,不是bitmap的形式,当图片以bitmap的形式存在时,其占用的内存会瞬间 变大, 我试过500k文件形式的图片加载到内存,以bitmap形式存在时,占用内存将近10m,当然这个增大的倍数并不是固定的

检测图片三种形式大小的方法:

文件形式: file.length()

流的形式: 讲图片文件读到内存输入流中,看它的byte数

bitmap: bitmap.getbytecount()

二.常见的压缩方式

1. 将图片保存到本地时进行压缩, 即将图片从bitmap形式变为file形式时进行压缩,

特点是:  file形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 bitmap是,它占用的内存并没有改变  

方法说明: 该方法是压缩图片的质量, 注意它不会减少图片的像素,比方说, 你的图片是300k的, 1280*700像素的, 经过该方法压缩后, file形式的图片是在100以下, 以方便上传服务器, 但是你bitmapfactory.decodefile到内存中,变成bitmap时,它的像素仍然是1280*700, 计算图片像素的方法是 bitmap.getwidth()和bitmap.getheight(), 图片是由像素组成的, 每个像素又包含什么呢? 熟悉ps的人知道, 图片是有色相,明度和饱和度构成的.

public static void compressbmptofile(bitmap bmp,file file){ 
    bytearrayoutputstream baos = new bytearrayoutputstream(); 
    int options = 80;//个人喜欢从80开始, 
    bmp.compress(bitmap.compressformat.jpeg, options, baos); 
    while (baos.tobytearray().length / 1024 > 100) {  
      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(); 
    } 
  } 

该方法的官方文档也解释说, 它会让图片重新构造, 但是有可能图像的位深(即色深)和每个像素的透明度会变化,jpeg onlysupports opaque(不透明), 也就是说以jpeg格式压缩后, 原来图片中透明的元素将消失.所以这种格式很可能造成失真

既然它是改变了图片的显示质量, 达到了对file形式的图片进行压缩, 图片的像素没有改变的话, 那重新读取经过压缩的file为bitmap时, 它占用的内存并不会少.(不相信的可以试试)

因为: bitmap.getbytecount() 是计算它的像素所占用的内存, 请看官方解释: returns the number of bytes used to store this bitmap's pixels.

2.   将图片从本地读到内存时,进行压缩 ,即图片从file形式变为bitmap形式

特点: 通过设置采样率, 减少图片的像素, 达到对内存中的bitmap进行压缩

先看一个方法: 该方法是对内存中的bitmap进行质量上的压缩, 由上面的理论可以得出该方法是无效的, 而且也是没有必要的,因为你已经将它读到内存中了,再压缩多此一举, 尽管在获取系统相册图片时,某些手机会直接返回一个bitmap,但是这种情况下, 返回的bitmap都是经过压缩的, 它不可能直接返回一个原声的bitmap形式的图片, 后果可想而知

方法说明: 该方法就是对bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少bitmap的像素, 从而减少了它所占用的内存

private bitmap compressbmpfrombmp(bitmap image) { 
    bytearrayoutputstream baos = new bytearrayoutputstream(); 
    int options = 100; 
    image.compress(bitmap.compressformat.jpeg, 100, baos); 
    while (baos.tobytearray().length / 1024 > 100) {  
      baos.reset(); 
      options -= 10; 
      image.compress(bitmap.compressformat.jpeg, options, baos); 
    } 
    bytearrayinputstream isbm = new bytearrayinputstream(baos.tobytearray()); 
    bitmap bitmap = bitmapfactory.decodestream(isbm, null, null); 
    return 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; 
  } 

分享个按照图片尺寸压缩:

public static void compresspicture(string srcpath, string despath) { 
    fileoutputstream fos = null; 
    bitmapfactoryoptions op = new bitmapfactoryoptions(); 
 
    // 开始读入图片,此时把optionsinjustdecodebounds 设回true了 
    opinjustdecodebounds = true; 
    bitmap bitmap = bitmapfactorydecodefile(srcpath, op); 
    opinjustdecodebounds = false; 
 
    // 缩放图片的尺寸 
    float w = opoutwidth; 
    float h = opoutheight; 
    float hh = 1024f;// 
    float ww = 1024f;// 
    // 最长宽度或高度1024 
    float be = 0f; 
    if (w > h && w > ww) { 
      be = (float) (w / ww); 
    } else if (w < h && h > hh) { 
      be = (float) (h / hh); 
    } 
    if (be <= 0) { 
      be = 0f; 
    } 
    opinsamplesize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小 
    // 重新读入图片,注意此时已经把optionsinjustdecodebounds 设回false了 
    bitmap = bitmapfactorydecodefile(srcpath, op); 
    int deswidth = (int) (w / be); 
    int desheight = (int) (h / be); 
    bitmap = bitmapcreatescaledbitmap(bitmap, deswidth, desheight, true); 
    try { 
      fos = new fileoutputstream(despath); 
      if (bitmap != null) { 
        bitmapcompress(bitmapcompressformatjpeg, 100, fos); 
      } 
    } catch (filenotfoundexception e) { 
      eprintstacktrace(); 
    } 
  } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网