編輯:Android 資訊
Android 上的圖片壓縮,歸根結底就兩條路:質量壓縮和像素壓縮。前者主要用在上傳場景,把體積壓下來省帶寬;後者常用於本地縮略圖展示,目的是別讓一張大圖把內存撐爆。兩者的實現方式和影響面完全不同,值得分開講。
質量壓縮的核心只有一個方法:
public boolean compress(CompressFormat format, int quality, OutputStream stream) {}
它屬於 Bitmap 類。第一個參數指定壓縮格式,Android 提供了三種可選:
public enum CompressFormat { JPEG (0), PNG (1), WEBP (2); CompressFormat(int nativeInt) { this.nativeInt = nativeInt; } final int nativeInt; }
第二個參數是質量的關鍵。取值範圍 0 到 100,數字越小壓得越狠。第三個參數則是壓縮結果的落點,數據會被寫入這個 OutputStream。
還是看代碼更直觀:
public byte [] compressBitmap(Bitmap bitmap,int max){ int quality = 100; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,quality,byteArrayOutputStream); while (byteArrayOutputStream.toByteArray().length / 1024 > max){ byteArrayOutputStream.reset(); quality = quality -10; bitmap.compress(Bitmap.CompressFormat.JPEG,quality,byteArrayOutputStream); } return byteArrayOutputStream.toByteArray(); }
第一個參數是待處理的 bitmap,不必多說。第二個參數是期望的體積上限(單位 KB)。循環裡每壓一次就把 quality 往下調 10,直到降到目標以內,最後返回 byte 數組。拿到這個數組,後續想轉成 File 還是 Bitmap 都很方便。
這裡有一點必須強調:質量壓縮改變的是編碼質量和文件體積,像素本身並沒有變化。也就是說圖片的分辨率保持原樣,解釋碼後得到的 Bitmap 尺寸和原圖一致。
像素壓縮顧名思義,壓的是像素。用到的核心方法是:
public static Bitmap decodeFile(String pathName, Options opts) { Bitmap bm = null; InputStream stream = null; try { stream = new FileInputStream(pathName); bm = decodeStream(stream, null, opts); } catch (Exception e) { /* do nothing. If the exception happened on open, bm will be null. */ Log.e("BitmapFactory", "Unable to decode stream: " + e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // do nothing here } } } return bm; }
這是 BitmapFactory 的靜態方法。第一個參數是文件絕對路徑,第二個參數 Options 才是主角。Options 是 BitmapFactory 的靜態內部類,其中有兩個屬性至關重要:
/** * If set to true, the decoder will return null (no bitmap), but * the out... fields will still be set, allowing the caller to query * the bitmap without having to allocate the memory for its pixels. */ public boolean inJustDecodeBounds; /** * If set to a value > 1, requests the decoder to subsample the original * image, returning a smaller image to save memory. The sample size is * the number of pixels in either dimension that correspond to a single * pixel in the decoded bitmap. For example, inSampleSize == 4 returns * an image that is 1/4 the width/height of the original, and 1/16 the * number of pixels. Any value <= 1 is treated the same as 1. Note: the * decoder uses a final value based on powers of 2, any other value will * be rounded down to the nearest power of 2. */ public int inSampleSize;
inJustDecodeBounds:設為 true 時,decodeFile 只解析圖片頭部信息、返回 null,但會把 outWidth、outHeight 這類尺寸信息填好。這讓我們能在不真正分配像素內存的前提下先探明原圖尺寸。
inSampleSize:縮放比例。大於 1 表示縮小,比如 inSampleSize == 4 意味着寬高各縮為四分之一、總像素變為十六分之一;小於等於 1 的效果等同於 1。要注意的是,解碼器內部只認 2 的冪次,其他數值會被向下取到最近的 2 的冪。
理解了這兩個屬性,網上到處可見的那段像素壓縮代碼就很好讀了:
private Bitmap getimage(String srcPath) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); //開始讀入圖片,此時把options.inJustDecodeBounds 設回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此時返回bm為空 newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; //現在主流手機比較多是800*480分辨率,所以高和寬我們設置為 float hh = 800f;//這裡設置高度為800f float ww = 480f;//這裡設置寬度為480f //縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可 int be = 1;//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;//設置縮放比例 //重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); return bitmap; }
整個流程是「兩次解碼」:第一次只讀尺寸不分配像素,算出需要的縮放倍數,第二次帶著 inSampleSize 真正解碼。這樣既拿到了目標尺寸,又避免了把原圖完整載入內存造成的 OOM。
實踐中兩種壓縮常常配合使用:先用像素壓縮把尺寸降到合理範圍,再用質量壓縮把體積壓到目標以內,兼顧清晰度與流量。
Android ANR 完全解析:成因、避免與定位
ANR 是 Android 開發中常見的穩定度問題,全名是 Application Not Responding。當應用無法在系統要求時間內回應輸入或廣播處理時,系統可能
Android 單元測試研究與實踐
Android 單元測試介紹身處高速迭代開發中的 Android 項目,往往需要比黑盒測試更可靠的質量保障,這正是單元測試的用武之地。單元測試周期性地對項目進行函數級別的
Android 平台關鍵字驅動自動化測試的實踐思路
桌面軟件與瀏覽器端的自動化測試經過十餘年打磨,無論工具鏈還是項目管理體制都日趨成熟;相比之下,移動端應用的自動化測試起步才兩三年,很多做法仍停留在摸索階段。但需求爆發的苗
最詳盡的 Android Toolbar 開發實踐與踩坑總結
年前我發過一篇介紹 Translucent System Bar 特性的文章《Translucent System Bar 的最佳實踐》,收到不少開發者的關注和反饋。今天