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

Android 從 Assets 讀取圖片檔案完整實作

     編輯:程式設計綜合問答

Assets 目錄適合存放應用打包時固定的資源檔(如預設圖片、設定檔、字型)。讀取方式需透過 AssetManager.open() 取得 InputStream,再經 BitmapFactory.decodeStream() 解碼為 Bitmap。注意資源路徑區分大小寫,且不支援子目錄遞迴列舉。

標準讀取流程


public Bitmap loadBitmapFromAssets(Context context, String fileName) {
    InputStream is = null;
    try {
        // 路徑相對於 assets 根目錄,如 "images/logo.png"
        is = context.getAssets().open(fileName);
        return BitmapFactory.decodeStream(is);
    } catch (IOException e) {
        Log.e("Assets", "Load bitmap failed: " + fileName, e);
        return null;
    } finally {
        if (is != null) {
            try { is.close(); } catch (IOException ignored) {}
        }
    }
}

使用範例


// 佈局檔
<ImageView
    android:id="@+id/ivLogo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

// Activity/Fragment
ImageView ivLogo = findViewById(R.id.ivLogo);
Bitmap bitmap = loadBitmapFromAssets(this, "brand/logo.png");
if (bitmap != null) {
    ivLogo.setImageBitmap(bitmap);
}

進階優化建議

  • 大圖採樣:使用 BitmapFactory.Options.inSampleSize 降低記憶體佔用,避免 OOM。
  • 快取策略:常用圖片可載入後存入 LruCache 或磁碟快取,避免重複解碼。
  • 非同步載入:大量或大尺寸圖片應在背景執行緒解碼,完成後回主執行緒更新 UI。
  • WebP 格式:優先使用 WebP 替代 PNG/JPG,減小 APK 體積並加快解碼。

常見錯誤排查

現象可能原因解決
FileNotFoundException路徑大小寫錯誤、檔案未打包進 APK確認 assets 目錄結構、Build 輸出 APK 解壓檢查
decodeStream 回傳 null檔案損壞、格式不支援、流已關閉驗證檔案完整性、確保流在 decode 前未關閉
ANR主執行緒解碼大圖移至背景執行緒、加入 inSampleSize

善用 Assets 機制,能讓應用離線也能呈現豐富視覺資源,且不佔用內部儲存空間。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved