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

Android 圖片緩存系列:Bitmap 與 BitmapFactory 詳解(一)

編輯:關於 Android 程式設計

準備研究圖片緩存框架之前,先把基礎打牢更為妥當。本篇聚焦兩個最核心的類:Bitmap 與 BitmapFactory。

Bitmap 類

Bitmap 是 Android 圖像處理的核心類,用它可以讀取圖像信息,完成剪切、旋轉、縮放等操作,並按指定格式保存為文件。

常用方法:

· public void recycle() 回收位圖佔用的內存,把對象標記為 Dead

· public final boolean isRecycled() 判斷內存是否已釋放

· public final int getWidth() / getHeight() 獲取寬高

· public final boolean isMutable() 判斷圖像是否可修改

· getScaledWidth(Canvas) / getScaledHeight(Canvas) 獲取密度轉換後的寬高

· public boolean compress(CompressFormat format, int quality, OutputStream stream) 按指定格式與品質輸出為流。format 取 PNG 或 JPEG;quality 範圍 0-100,數值越低壓縮越狠,對 PNG 這類無損格式則忽略此項

· createBitmap(Bitmap src) 以 src 為原圖生成不可變的新圖像

· createScaledBitmap(src, dstWidth, dstHeight, filter) 縮放並指定是否可變

· createBitmap(int width, int height, Config config) 按指定格式與尺寸新建位圖

· createBitmap(Bitmap source, int x, int y, int width, int height) 從原圖的指定區域裁剪出新圖

BitmapFactory 工廠類

Options 參數類是控制解碼行為的關鍵,常用的有:

· inJustDecodeBounds 設為 true 時不解碼像素、不分配內存,只返回尺寸信息

· inSampleSize 抽樣縮放倍數

· outWidth / outHeight 解碼後的實際寬高

· inDensity / inTargetDensity 源與目標的像素密度,配合 inScaled 使用

· inTempStorage 臨時文件緩衝

· inScaled 設為 true 時按 inDensity 到 inTargetDensity 的比例縮放

· inDither 為 true 時解碼器嘗試抖動

· inPreferredConfig 指定解碼後的位圖配置

· outMimeType 輸出圖像的 MIME 類型

· inPurgeable 內存緊張時像素空間是否可被回收

· inInputShareable 在 inPurgeable 為 true 時生效,是否可以共享 InputStream

· inPreferQualityOverSpeed 為 true 則優先保證質量而非解碼速度

· inMutable 配置解碼結果是否可修改

· inScreenDensity 當前屏幕的像素密度

工廠方法對應不同的數據來源:

· decodeFile(String pathName, Options opts) 從文件讀取

· decodeStream(InputStream is, Rect outPadding, Options opts) 從輸入流讀取

· decodeResource(Resources res, int id, Options opts) 從資源文件讀取

· decodeByteArray(byte[] data, int offset, int length, Options opts) 從字節數組讀取

· decodeFileDescriptor(FileDescriptor fd, ...) 從文件描述符讀取,直接調用 JNI,效率更高

Bitmap.Config 決定每個像素佔多少字節,位數越高色彩越豐富,內存佔用也越大:

· ALPHA_8 8 位 Alpha,每像素 1 byte

· ARGB_4444 16 位,每像素 2 byte

· ARGB_8888 32 位,每像素 4 byte

· RGB_565 16 位,每像素 2 byte

由此可得內存估算公式:

一張圖片佔用的內存 = 圖片長度 × 圖片寬度 × 單位像素字節數

這個公式很值得記住。一張 4000×3000 的拍照原圖,按 ARGB_8888 解碼就是約 48MB,瞬間就能把應用撐爆——這也解釋了為什麼「先取尺寸再降採樣」是加載大圖的必經步驟。

讀取圖片的幾種方式

1)從文件讀取(方式一)

核心套路是兩段式解碼:先設 inJustDecodeBounds = true 拿到原始尺寸,算出合適的 inSampleSize,再關閉該標志真正解碼。

 /** * 獲取縮放後的本地圖片 * * @param filePath 文件路徑 * @param width 寬 * @param height 高 * @return */ public static Bitmap readBitmapFromFile(String filePath, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeFile(filePath, options); } 

2)從文件讀取(方式二,效率更高)

 /** * 獲取縮放後的本地圖片 * * @param filePath 文件路徑 * @param width 寬 * @param height 高 * @return */ public static Bitmap readBitmapFromFileDescriptor(String filePath, int width, int height) { try { FileInputStream fis = new FileInputStream(filePath); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options); } catch (Exception ex) { } return null; } 

筆者用同一批圖片各生成 10 張做對比,CPU 佔用和內存消耗相差無幾,方式二的耗時略短,因此建議優先採用。

 start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromFile(filePath, 400, 400); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeFile--time-->" + (end - start)); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromFileDescriptor(filePath, 400, 400); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeFileDescriptor--time-->" + (end - start)); 

3)從輸入流讀取

 /** * 獲取縮放後的本地圖片 * * @param ins 輸入流 * @param width 寬 * @param height 高 * @return */ public static Bitmap readBitmapFromInputStream(InputStream ins, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(ins, null, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeStream(ins, null, options); } 

這裡有個坑:InputStream 只能讀一次,兩段式解碼時第二次會拿到空數據。實用做法是先把流讀成字節數組,再分別用 decodeByteArray 解兩次,或者對文件路徑改用方式二。

4)從資源文件讀取

 public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(resources, resourcesId, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeResource(resources, resourcesId, options); } 

這種方式比較耗內存,建議改用 decodeStream:

 public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) { InputStream ins = resources.openRawResource(resourcesId); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(ins, null, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeStream(ins, null, options); } 

兩者的差異值得記住:decodeResource 加載的圖片可能會被縮放,而這個縮放是在 Java 層完成的,效率較低且要消耗 Java 堆內存,大量使用容易 OOM;decodeStream 不做縮放,佔用更少、效率更高。因此對性能敏感時用 decodeStream;性能要求不高且希望利用系統自適應縮放時,可以用 decodeResource。

 start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromResource(getResources(), R.mipmap.ic_app_center_banner, 400, 400); Log.e(TAG, "BitmapFactory decodeResource--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeResource--time-->" + (end - start)); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromResource1(getResources(), R.mipmap.ic_app_center_banner, 400, 400); Log.e(TAG, "BitmapFactory decodeStream--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeStream--time-->" + (end - start)); 

5)從字節數組讀取

 public static Bitmap readBitmapFromByteArray(byte[] data, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeByteArray(data, 0, data.length, options); } 

6)從 assets 讀取

 /** * 獲取縮放後的本地圖片 * * @param filePath 文件路徑 * @return */ public static Bitmap readBitmapFromAssetsFile(Context context, String filePath) { Bitmap image = null; AssetManager am = context.getResources().getAssets(); try { InputStream is = am.open(filePath); image = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return image; } 

常用處理操作

保存為文件

 public static void writeBitmapToFile(String filePath, Bitmap b, int quality) { try { File desFile = new File(filePath); FileOutputStream fos = new FileOutputStream(desFile); BufferedOutputStream bos = new BufferedOutputStream(fos); b.compress(Bitmap.CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } 

質量壓縮

 private static Bitmap compressImage(Bitmap image) { if (image == null) { return null; } ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); ByteArrayInputStream isBm = new ByteArrayInputStream(bytes); Bitmap bitmap = BitmapFactory.decodeStream(isBm); return bitmap; } catch (OutOfMemoryError e) { } finally { try { if (baos != null) { baos.close(); } } catch (IOException e) { } } return null; } 

需要說明的是,這種「壓縮再解碼」的做法只改變了文件體積,解碼出來的位圖尺寸並未減小,內存佔用幾乎不變。真正能降內存的是前面用的 inSampleSize 降採樣。

等比縮放

 /** * 根據scale生成一張圖片 * * @param bitmap * @param scale 等比縮放值 * @return */ public static Bitmap bitmapScale(Bitmap bitmap, float scale) { Matrix matrix = new Matrix(); matrix.postScale(scale, scale); // 長和寬放大縮小的比例 Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); return resizeBmp; } 

讀取照片旋轉角度

 /** * 讀取照片exif信息中的旋轉角度 * * @param path 照片路徑 * @return角度 */ private static int readPictureDegree(String path) { if (TextUtils.isEmpty(path)) { return 0; } int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (Exception e) { } return degree; } 

按角度旋轉

 private static Bitmap rotateBitmap(Bitmap b, float rotateDegree) { if (b == null) { return null; } Matrix matrix = new Matrix(); matrix.postRotate(rotateDegree); Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); return rotaBitmap; } 

EXIF 與旋轉這兩段通常成對出現:手機拍照的圖片方向信息存在 EXIF 裡,不解讀直接顯示就會橫躺著。

Bitmap 轉字節數組

 public byte[] bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 

Bitmap 與 Drawable 互轉

 public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) { Drawable drawable = new BitmapDrawable(resources, bm); return drawable; }
 public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }

為什麼緩存 Drawable 而不是 Bitmap

Afinal 和 Xutils 出自同一作者,後者是前者的升級版。有意思的是,AFinal 的內存緩存用的是 Bitmap,而 Xutils 卻把緩存對象換成了 Drawable。這是為什麼?寫個對比測試:

 List<Bitmap> bitmaps = new ArrayList<>(); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { Bitmap bitmap = BitmapUtils.readBitMap(this, R.mipmap.ic_app_center_banner); bitmaps.add(bitmap); Log.e(TAG, "BitmapFactory Bitmap--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory Bitmap--time-->" + (end - start)); List<Drawable> drawables = new ArrayList<>(); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { Drawable drawable = getResources().getDrawable(R.mipmap.ic_app_center_banner); drawables.add(drawable); Log.e(TAG, "BitmapFactory Drawable--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory Drawable--time-->" + (end - start)); 

測試數據 1000,同一張圖片:

結果說明 Drawable 相對 Bitmap 確有明顯的內存優勢。這也是主流圖片緩存框架在內存緩存這一層選擇 Drawable 作為緩存對象的原因。

小結:圖片處理的基礎知識暫時梳理到這裡,後續再補充。理解了 Bitmap 的內存計算方式和降採樣機制,再看各種緩存框架的設計就會通透很多。

以上就是本文的全部內容,希望對大家的學習有所幫助。

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