Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Bitmap 壓縮方法的選擇與踩坑詳解

編輯:關於 Android 程式設計

剛修 Bug 時碰到一個問題,先把經過描述一下。

1. 測試反饋:分享文章到微信失敗,分享到 QQ 卻成功。

於是定位到微信分享介面。

2. 換成分享其他文章到微信卻成功了。

說明介面本身沒問題——幸好沒急著去查介面。

3. 中斷點跟進微信分享,發現是「突然壓縮失敗」。

問題出在程式碼寫法上,下面會拆解。

4. 找到根因:微信對分享縮圖的大小有 32K 的限制,而程式碼是把文章的第一張圖拿去壓縮,圖片太大、壓縮邏輯也有缺陷。

開始解決問題

這裡有兩種思路:
1)由後端介面直接提供文章對應的分享內容,讓編輯在編輯文章時就對這些資料做好限制。

 { "title":"how to begain Android?", "content":"do it, do it, do it", "picture":"https://192.168.0.1/pic/2015/09/02/share_thumb.jpg" ... ... } 

其中 picture 欄位就是一張 <32K 的縮圖。

就我目前的水平而言,個人認為這是更好的做法——不是為了 Android 端省事,而是從整個專案後續的擴展與規劃來看都比較理想。當然水平有限,也許看得不夠遠,歡迎指正。

2)在客戶端對取得的文章圖片進行壓縮。

由於當前專案無法改動介面,只能走圖片壓縮這條路,於是就踩到了上面提到的坑。先看原本寫的壓縮程式碼:

----可能出錯的程式碼----

 int options = 100; ByteArrayOutputStream outputs = new ByteArrayOutputStream(); oBitmap.compress(Bitmap.CompressFormat.JPEG, options, outputs); // while ( outputs.toByteArray().length / 1024 > 32 ) { outputs.reset(); oBitmap.compress(Bitmap.CompressFormat.JPEG, options, outputs); options -= 10 ; } ByteArrayInputStream inputs = new ByteArrayInputStream(outputs.toByteArray()); Bitmap bitmap = BitmapFactory.decodeStream(inputs, null , null ); 

這裡用 bitmap 的 compress() 方法做了所謂的「質量壓縮」,控制參數就是 options。但出問題的地方恰恰也是它:當圖片非常大時,即使 options 已經降到 0,圖片仍舊大於 32K,這時候 while 迴圈裡的 options 就會變成負數,再執行 compress() 便會拋出 throw new IllegalArgumentException("quality must be 0..100") 的錯誤。

原因在於:

用 compress() 的 options 進行壓縮,本質上並不會丟棄像素,只是透過修改透明度等其他屬性來改變圖片大小,所以它無法無限壓縮,降到某個值之後就不再變小了。

解決:

我最先想到的是:質量壓縮後,若 options 為 0 時仍大於 32K,就改用取樣率壓縮。

 BitmapFactory.Options newOpts = new BitmapFactory.Options(); newOpts.inSampleSize = 2; bitmap = BitmapFactory.decodeFile(picturePath, newOpts); 

每次判斷 bitmap 大小,對 inSampleSize 做 +1 或 -1(不能小於 1)的調整即可。但 inSampleSize 是 int 型別,圖片很大時,1/2、1/3、1/4 之間的落差還是偏大,於是只能放棄,最後改採縮放的方法。先上程式碼:

 public static byte[] WeChatBitmapToByteArray(Bitmap bmp, boolean needRecycle) { // 首先進行一次大范圍的壓縮 ByteArrayOutputStream output = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, output); float zoom = (float)Math.sqrt(32 * 1024 / (float)output.toByteArray().length); //獲取縮放比例 // 設置矩陣數據 Matrix matrix = new Matrix(); matrix.setScale(zoom, zoom); // 根據矩陣數據進行新bitmap的創建 Bitmap resultBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); output.reset(); resultBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output); // 如果進行了上面的壓縮後,依舊大於32K,就進行小范圍的微調壓縮 while(output.toByteArray().length > 32 * 1024){ matrix.setScale(0.9f, 0.9f);//每次縮小 1/10 resultBitmap = Bitmap.createBitmap( resultBitmap, 0, 0, resultBitmap.getWidth(), resultBitmap.getHeight(), matrix,true); output.reset(); resultBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output); } return result; } 

至此,暫且補上了這個一開始寫法不規範所埋下的坑。以上思路綜合自書籍與網路上的資料,並做了一些整合。如果你也遇到同樣的問題,又剛好看到這篇文章,希望能幫上一點小忙。

希望本文能幫助到有需要的同學。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved