在列表展示、圖片選擇器、圖庫掃描等場景中,需要快速獲取大量圖片的寬高以計算佈局、預覽縮略圖、判斷方向,但絕不能將完整像素數據載入內存 (極易 OOM)。BitmapFactory.Options.inJustDecodeBounds = true 是官方提供的零內存解碼方案,本文深度解析其原理、用法、陷阱與封裝最佳實踐。
inJustDecodeBounds = true 時,BitmapFactory.decodeXxx() 僅解析圖片文件頭 (PNG IHDR、JPEG SOF、WebP VP8 Header 等),填充 Options.outWidth、outHeight、outMimeType,不分配像素內存、不返回 Bitmap 對象 (返回 null)。
public static ImageSize getImageSize(String filePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 關鍵:不載入像素
BitmapFactory.decodeFile(filePath, options);
// options.outWidth / outHeight 已填充
// options.outMimeType 可獲取 "image/jpeg", "image/png", "image/webp" 等
return new ImageSize(options.outWidth, options.outHeight, options.outMimeType);
}
// 支持多種數據源
public static ImageSize getImageSize(InputStream is) {
Options opts = new Options();
opts.inJustDecodeBounds = true;
// 注意:InputStream 必須支持 mark/reset,或傳入 BufferedInputStream
BitmapFactory.decodeStream(new BufferedInputStream(is), null, opts);
return new ImageSize(opts.outWidth, opts.outHeight, opts.outMimeType);
}
public static ImageSize getImageSize(byte[] data) {
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, opts);
return new ImageSize(opts.outWidth, opts.outHeight, opts.outMimeType);
}
public static ImageSize getImageSize(FileDescriptor fd) {
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd, null, opts);
return new ImageSize(opts.outWidth, opts.outHeight, opts.outMimeType);
}
public static ImageSize getImageSize(ContentResolver resolver, Uri uri) {
try (InputStream is = resolver.openInputStream(uri)) {
return getImageSize(is);
} catch (IOException e) {
return null;
}
}
static class ImageSize {
final int width, height;
final String mimeType;
ImageSize(int w, int h, String mime) { width = w; height = h; mimeType = mime; }
float aspectRatio() { return height == 0 ? 0 : (float) width / height; }
}
核心邏輯:先 inJustDecodeBounds=true 獲取原始尺寸 → 計算 inSampleSize (2 的冪次) → 再 inJustDecodeBounds=false 解碼縮略圖。
public static Bitmap decodeSampledBitmap(String path, int reqWidth, int reqHeight) {
// 1. 獲取原始尺寸
Options boundsOpts = new Options();
boundsOpts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, boundsOpts);
// 2. 計算最優 inSampleSize
boundsOpts.inSampleSize = calculateInSampleSize(boundsOpts, reqWidth, reqHeight);
// 3. 實際解碼 (可選配置)
boundsOpts.inJustDecodeBounds = false;
boundsOpts.inPreferredConfig = Bitmap.Config.RGB_565; // 節省 50% 內存
boundsOpts.inMutable = true; // 允許 inBitmap 復用
// boundsOpts.inBitmap = reusableBitmap; // API 19+ 復用策略
return BitmapFactory.decodeFile(path, boundsOpts);
}
public static int calculateInSampleSize(Options opts, int reqWidth, int reqHeight) {
if (reqWidth <= 0 || reqHeight <= 0) return 1;
int inSampleSize = 1;
if (opts.outHeight > reqHeight || opts.outWidth > reqWidth) {
int halfH = opts.outHeight / 2;
int halfW = opts.outWidth / 2;
while ((halfH / inSampleSize) >= reqHeight && (halfW / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
| 坑點 | 現象 | 原因 | 解決方案 |
|---|---|---|---|
| InputStream 不支持 mark/reset | decodeStream 返回 null、尺寸為 0 | 網絡流/加密流無 mark 能力 | 包裝 BufferedInputStream(is, 16KB) 或 先拷貝到文件/字節數組 |
| outWidth/outHeight 為 -1 或 0 | 解析失敗 | 文件損壞、格式不支持、路徑錯誤、輸入流已關閉 | 檢查文件完整性、捕獲異常、驗證 MIME 類型 |
| 旋轉圖片尺寸顛倒 | 獲取寬高與實際顯示不符 | EXIF Orientation 標籤導致邏輯寬高交換 | 使用 ExifInterface 讀取 orientation,或 Glide/ExoPlayer 自動處理 |
| 頻繁調用造成 IO 瓶頸 | 列表快速滑動時反覆讀取文件頭 | 緩存尺寸信息 (LruCache key=path/uri)、預掃描構建索引庫 | |
| ContentResolver openInputStream 閃退 | 無權限訪問 Uri | Intent.FLAG_GRANT_READ_URI_PERMISSION、takePersistableUriPermission |
// Context 擴展
suspend fun Context.getImageSize(uri: Uri): ImageSize? = withContext(Dispatchers.IO) {
try {
contentResolver.openInputStream(uri)?.use { inputStream ->
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeStream(BufferedInputStream(inputStream), null, opts)
ImageSize(opts.outWidth, opts.outHeight, opts.outMimeType)
}
} catch (e: Exception) {
null
}
}
// 批量預掃描 (MediaStore 查詢更高效)
suspend fun Context.scanMediaStoreImages(): List = withContext(Dispatchers.IO) {
val projection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.WIDTH, // 直接從數據庫讀取,無需解碼文件頭!
MediaStore.Images.Media.HEIGHT,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.DATA, // API 29+ 可能為空
MediaStore.Images.Media.DATE_ADDED
)
val cursor = contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC"
)
return@withContext cursor?.use { c ->
val list = mutableListOf()
val idIdx = c.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val wIdx = c.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)
val hIdx = c.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT)
while (c.moveToNext()) {
list.add(ImageInfo(
id = c.getLong(idIdx),
width = c.getInt(wIdx),
height = c.getInt(hIdx),
mimeType = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE))
))
}
list
} ?: emptyList()
}
掌握這一技術,是從「會用圖片加載庫」進階到「能寫圖片加載庫、能解決 OOM 難題」的關鍵一步。