首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Assets 圖片加載失效?一文解決 BitmapFactory 解碼陷阱

     編輯:程式設計綜合問答

常見錯誤現象

代碼無報錯但 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);
}

進階避坑指南

1. 大圖分塊加載

// 超過 2048x2048 需使用 BitmapRegionDecoder
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
Rect rect = new Rect(0, 0, 512, 512);
Bitmap region = decoder.decodeRegion(rect, options);

2. 內存優化策略

場景inSampleSize配置建議
縮圖列表計算縮放比RGB_565 + inPurgeable=true
全屏展示1 或 2ARGB_8888 + 磁盤緩存
圖片編輯1ARGB_8888 + 內存緩存

3. 現代化替代方案

  • Glide:Glide.with(this).load("file:///android_asset/test3.png").into(imageView)
  • Coil (Kotlin):imageView.load("asset://test3.png")
  • 自定義 AssetProvider:實現 ContentProvider 統一資源訪問

調試檢查清單

  1. 文件名大小寫敏感(Assets 區分大小寫)
  2. 路徑包含子目錄時需完整相對路徑 "images/icon.png"
  3. 構建時確認 assets 目錄已打包進 APK(APK Analyzer 驗證)
  4. 模擬器/真機存儲權限不影響 Assets 讀取
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved