代碼無報錯但 ImageView 顯示空白,典型錯誤代碼:
// 錯誤示範:流未關閉、異常吞噬
AssetManager mngr = context.getResources().getAssets();
InputStream is = mngr.open("test3.png");
Bitmap bitmap = BitmapFactory.decodeStream(is);
// 缺少 is.close() 導致文件句柄泄漏
imageView.setImageBitmap(bitmap);
public static Bitmap loadFromAssets(Context context, String fileName) {
InputStream is = null;
try {
is = context.getAssets().open(fileName);
// 關鍵:設置解碼選項防止 OOM
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565; // 節省 50% 內存
return BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
Log.e("AssetsLoader", "加載失敗: " + fileName, e);
return null;
} finally {
if (is != null) {
try { is.close(); } catch (IOException ignored) {}
}
}
}
// 調用示例
Bitmap bitmap = loadFromAssets(this, "images/test3.png");
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
// 超過 2048x2048 需使用 BitmapRegionDecoder
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
Rect rect = new Rect(0, 0, 512, 512);
Bitmap region = decoder.decodeRegion(rect, options);
| 場景 | inSampleSize | 配置建議 |
|---|---|---|
| 縮圖列表 | 計算縮放比 | RGB_565 + inPurgeable=true |
| 全屏展示 | 1 或 2 | ARGB_8888 + 磁盤緩存 |
| 圖片編輯 | 1 | ARGB_8888 + 內存緩存 |
Glide.with(this).load("file:///android_asset/test3.png").into(imageView)imageView.load("asset://test3.png")ContentProvider 統一資源訪問"images/icon.png"assets 目錄已打包進 APK(APK Analyzer 驗證)