Android質量壓縮和尺寸壓縮

在網上調查了圖片壓縮的方法並實裝後,大致上可以認爲有兩類壓縮:質量壓縮(不改變圖片的尺寸)和尺寸壓縮(相當於是像素上的壓縮);質量壓縮一般可用於上傳大圖前的處理,這樣就可以節省一定的流量,畢竟現在的手機拍照都能達到3M左右了,尺寸壓縮一般可用於生成縮略圖。
兩種方法都實裝在了我的項目中,結果卻發現在質量壓縮的模塊中,本來1.9M的圖片壓縮後反而變成3M多了,很是奇怪,再做了進一步調查終於知道原因了。下面這個博客說的比較清晰:

android圖片壓縮總結

總結來看,圖片有三種存在形式:硬盤上時是file,網絡傳輸時是stream,內存中是stream或bitmap,所謂的質量壓縮,它其實只能實現對file的影響,你可以把一個file轉成bitmap再轉成file,或者直接將一個bitmap轉成file時,這個最終的file是被壓縮過的,但是中間的bitmap並沒有被壓縮(或者說幾乎沒有被壓縮,我不確定),因爲bigmap在內存中的大小是按像素計算的,也就是width * height,對於質量壓縮,並不會改變圖片的像素,所以就算質量被壓縮了,但是bitmap在內存的佔有率還是沒變小,但你做成file時,它確實變小了;

而尺寸壓縮由於是減小了圖片的像素,所以它直接對bitmap產生了影響,當然最終的file也是相對的變小了;

最後把自己總結的工具類貼出來:
[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import android.graphics.Bitmap;  
  9. import android.graphics.Bitmap.Config;  
  10. import android.graphics.BitmapFactory;  
  11.   
  12. /** 
  13.  * Image compress factory class 
  14.  *  
  15.  * @author  
  16.  * 
  17.  */  
  18. public class ImageFactory {  
  19.   
  20.     /** 
  21.      * Get bitmap from specified image path 
  22.      *  
  23.      * @param imgPath 
  24.      * @return 
  25.      */  
  26.     public Bitmap getBitmap(String imgPath) {  
  27.         // Get bitmap through image path  
  28.         BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  29.         newOpts.inJustDecodeBounds = false;  
  30.         newOpts.inPurgeable = true;  
  31.         newOpts.inInputShareable = true;  
  32.         // Do not compress  
  33.         newOpts.inSampleSize = 1;  
  34.         newOpts.inPreferredConfig = Config.RGB_565;  
  35.         return BitmapFactory.decodeFile(imgPath, newOpts);  
  36.     }  
  37.       
  38.     /** 
  39.      * Store bitmap into specified image path 
  40.      *  
  41.      * @param bitmap 
  42.      * @param outPath 
  43.      * @throws FileNotFoundException  
  44.      */  
  45.     public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {  
  46.         FileOutputStream os = new FileOutputStream(outPath);  
  47.         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);  
  48.     }  
  49.       
  50.     /** 
  51.      * Compress image by pixel, this will modify image width/height.  
  52.      * Used to get thumbnail 
  53.      *  
  54.      * @param imgPath image path 
  55.      * @param pixelW target pixel of width 
  56.      * @param pixelH target pixel of height 
  57.      * @return 
  58.      */  
  59.     public Bitmap ratio(String imgPath, float pixelW, float pixelH) {  
  60.         BitmapFactory.Options newOpts = new BitmapFactory.Options();    
  61.         // 開始讀入圖片,此時把options.inJustDecodeBounds 設回true,即只讀邊不讀內容  
  62.         newOpts.inJustDecodeBounds = true;  
  63.         newOpts.inPreferredConfig = Config.RGB_565;  
  64.         // Get bitmap info, but notice that bitmap is null now    
  65.         Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);  
  66.             
  67.         newOpts.inJustDecodeBounds = false;    
  68.         int w = newOpts.outWidth;    
  69.         int h = newOpts.outHeight;    
  70.         // 想要縮放的目標尺寸  
  71.         float hh = pixelH;// 設置高度爲240f時,可以明顯看到圖片縮小了  
  72.         float ww = pixelW;// 設置寬度爲120f,可以明顯看到圖片縮小了  
  73.         // 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可    
  74.         int be = 1;//be=1表示不縮放    
  75.         if (w > h && w > ww) {//如果寬度大的話根據寬度固定大小縮放    
  76.             be = (int) (newOpts.outWidth / ww);    
  77.         } else if (w < h && h > hh) {//如果高度高的話根據寬度固定大小縮放    
  78.             be = (int) (newOpts.outHeight / hh);    
  79.         }    
  80.         if (be <= 0) be = 1;    
  81.         newOpts.inSampleSize = be;//設置縮放比例  
  82.         // 開始壓縮圖片,注意此時已經把options.inJustDecodeBounds 設回false了  
  83.         bitmap = BitmapFactory.decodeFile(imgPath, newOpts);  
  84.         // 壓縮好比例大小後再進行質量壓縮  
  85. //        return compress(bitmap, maxSize); // 這裏再進行質量壓縮的意義不大,反而耗資源,刪除  
  86.         return bitmap;  
  87.     }  
  88.       
  89.     /** 
  90.      * Compress image by size, this will modify image width/height.  
  91.      * Used to get thumbnail 
  92.      *  
  93.      * @param image 
  94.      * @param pixelW target pixel of width 
  95.      * @param pixelH target pixel of height 
  96.      * @return 
  97.      */  
  98.     public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {  
  99.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  100.         image.compress(Bitmap.CompressFormat.JPEG, 100, os);  
  101.         if( os.toByteArray().length / 1024>1024) {//判斷如果圖片大於1M,進行壓縮避免在生成圖片(BitmapFactory.decodeStream)時溢出      
  102.             os.reset();//重置baos即清空baos    
  103.             image.compress(Bitmap.CompressFormat.JPEG, 50, os);//這裏壓縮50%,把壓縮後的數據存放到baos中    
  104.         }    
  105.         ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());    
  106.         BitmapFactory.Options newOpts = new BitmapFactory.Options();    
  107.         //開始讀入圖片,此時把options.inJustDecodeBounds 設回true了    
  108.         newOpts.inJustDecodeBounds = true;  
  109.         newOpts.inPreferredConfig = Config.RGB_565;  
  110.         Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);    
  111.         newOpts.inJustDecodeBounds = false;    
  112.         int w = newOpts.outWidth;    
  113.         int h = newOpts.outHeight;    
  114.         float hh = pixelH;// 設置高度爲240f時,可以明顯看到圖片縮小了  
  115.         float ww = pixelW;// 設置寬度爲120f,可以明顯看到圖片縮小了  
  116.         //縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可    
  117.         int be = 1;//be=1表示不縮放    
  118.         if (w > h && w > ww) {//如果寬度大的話根據寬度固定大小縮放    
  119.             be = (int) (newOpts.outWidth / ww);    
  120.         } else if (w < h && h > hh) {//如果高度高的話根據寬度固定大小縮放    
  121.             be = (int) (newOpts.outHeight / hh);    
  122.         }    
  123.         if (be <= 0) be = 1;    
  124.         newOpts.inSampleSize = be;//設置縮放比例    
  125.         //重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了    
  126.         is = new ByteArrayInputStream(os.toByteArray());    
  127.         bitmap = BitmapFactory.decodeStream(is, null, newOpts);  
  128.         //壓縮好比例大小後再進行質量壓縮  
  129. //      return compress(bitmap, maxSize); // 這裏再進行質量壓縮的意義不大,反而耗資源,刪除  
  130.         return bitmap;  
  131.     }  
  132.       
  133.     /** 
  134.      * Compress by quality,  and generate image to the path specified 
  135.      *  
  136.      * @param image 
  137.      * @param outPath 
  138.      * @param maxSize target will be compressed to be smaller than this size.(kb) 
  139.      * @throws IOException  
  140.      */  
  141.     public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {  
  142.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  143.         // scale  
  144.         int options = 100;  
  145.         // Store the bitmap into output stream(no compress)  
  146.         image.compress(Bitmap.CompressFormat.JPEG, options, os);    
  147.         // Compress by loop  
  148.         while ( os.toByteArray().length / 1024 > maxSize) {  
  149.             // Clean up os  
  150.             os.reset();  
  151.             // interval 10  
  152.             options -= 10;  
  153.             image.compress(Bitmap.CompressFormat.JPEG, options, os);  
  154.         }  
  155.           
  156.         // Generate compressed image file  
  157.         FileOutputStream fos = new FileOutputStream(outPath);    
  158.         fos.write(os.toByteArray());    
  159.         fos.flush();    
  160.         fos.close();    
  161.     }  
  162.       
  163.     /** 
  164.      * Compress by quality,  and generate image to the path specified 
  165.      *  
  166.      * @param imgPath 
  167.      * @param outPath 
  168.      * @param maxSize target will be compressed to be smaller than this size.(kb) 
  169.      * @param needsDelete Whether delete original file after compress 
  170.      * @throws IOException  
  171.      */  
  172.     public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {  
  173.         compressAndGenImage(getBitmap(imgPath), outPath, maxSize);  
  174.           
  175.         // Delete original file  
  176.         if (needsDelete) {  
  177.             File file = new File (imgPath);  
  178.             if (file.exists()) {  
  179.                 file.delete();  
  180.             }  
  181.         }  
  182.     }  
  183.       
  184.     /** 
  185.      * Ratio and generate thumb to the path specified 
  186.      *  
  187.      * @param image 
  188.      * @param outPath 
  189.      * @param pixelW target pixel of width 
  190.      * @param pixelH target pixel of height 
  191.      * @throws FileNotFoundException 
  192.      */  
  193.     public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {  
  194.         Bitmap bitmap = ratio(image, pixelW, pixelH);  
  195.         storeImage( bitmap, outPath);  
  196.     }  
  197.       
  198.     /** 
  199.      * Ratio and generate thumb to the path specified 
  200.      *  
  201.      * @param image 
  202.      * @param outPath 
  203.      * @param pixelW target pixel of width 
  204.      * @param pixelH target pixel of height 
  205.      * @param needsDelete Whether delete original file after compress 
  206.      * @throws FileNotFoundException 
  207.      */  
  208.     public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {  
  209.         Bitmap bitmap = ratio(imgPath, pixelW, pixelH);  
  210.         storeImage( bitmap, outPath);  
  211.           
  212.         // Delete original file  
  213.                 if (needsDelete) {  
  214.                     File file = new File (imgPath);  
  215.                     if (file.exists()) {  
  216.                         file.delete();  
  217.                     }  
  218.                 }  
  219.     }  
  220.       
  221. }  

延伸閱讀
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是,它佔用的內存並沒有改變   
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public static void compressBmpToFile(Bitmap bmp,File file){  
  2.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  3.         int options = 80;//個人喜歡從80開始,  
  4.         bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);  
  5.         while (baos.toByteArray().length / 1024 > 100) {   
  6.             baos.reset();  
  7.             options -= 10;  
  8.             bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);  
  9.         }  
  10.         try {  
  11.             FileOutputStream fos = new FileOutputStream(file);  
  12.             fos.write(baos.toByteArray());  
  13.             fos.flush();  
  14.             fos.close();  
  15.         } catch (Exception e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
方法說明: 該方法是壓縮圖片的質量, 注意它不會減少圖片的像素,比方說, 你的圖片是300K的, 1280*700像素的, 經過該方法壓縮後, File形式的圖片是在100以下, 以方便上傳服務器, 但是你BitmapFactory.decodeFile到內存中,變成Bitmap時,它的像素仍然是1280*700, 計算圖片像素的方法是 bitmap.getWidth()和bitmap.getHeight(), 圖片是由像素組成的, 每個像素又包含什麼呢? 熟悉PS的人知道, 圖片是有色相,明度和飽和度構成的. 

該方法的官方文檔也解釋說, 它會讓圖片重新構造, 但是有可能圖像的位深(即色深)和每個像素的透明度會變化,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形式的圖片, 後果可想而知
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. private Bitmap compressBmpFromBmp(Bitmap image) {  
  2.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  3.         int options = 100;  
  4.         image.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
  5.         while (baos.toByteArray().length / 1024 > 100) {   
  6.             baos.reset();  
  7.             options -= 10;  
  8.             image.compress(Bitmap.CompressFormat.JPEG, options, baos);  
  9.         }  
  10.         ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
  11.         Bitmap bitmap = BitmapFactory.decodeStream(isBm, nullnull);  
  12.         return bitmap;  
  13.     }  
  再看一個方法:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1.     private Bitmap compressImageFromFile(String srcPath) {  
  2.         BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  3.         newOpts.inJustDecodeBounds = true;//只讀邊,不讀內容  
  4.         Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
  5.   
  6.         newOpts.inJustDecodeBounds = false;  
  7.         int w = newOpts.outWidth;  
  8.         int h = newOpts.outHeight;  
  9.         float hh = 800f;//  
  10.         float ww = 480f;//  
  11.         int be = 1;  
  12.         if (w > h && w > ww) {  
  13.             be = (int) (newOpts.outWidth / ww);  
  14.         } else if (w < h && h > hh) {  
  15.             be = (int) (newOpts.outHeight / hh);  
  16.         }  
  17.         if (be <= 0)  
  18.             be = 1;  
  19.         newOpts.inSampleSize = be;//設置採樣率  
  20.           
  21.         newOpts.inPreferredConfig = Config.ARGB_8888;//該模式是默認的,可不設  
  22.         newOpts.inPurgeable = true;// 同時設置纔會有效  
  23.         newOpts.inInputShareable = true;//。當系統內存不夠時候圖片自動被回收  
  24.           
  25.         bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
  26. //      return compressBmpFromBmp(bitmap);//原來的方法調用了這個方法企圖進行二次壓縮  
  27.                                     //其實是無效的,大家儘管嘗試  
  28.         return bitmap;  
  29.     }  


方法說明: 該方法就是對Bitmap形式的圖片進行壓縮, 也就是通過設置採樣率, 減少Bitmap的像素, 從而減少了它所佔用的內存
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章