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

讀取 assets 目錄下的圖片資源

編輯:關於 Android 程式設計

兩個容易踩到的觀念

  1. assets 裡的檔案是打包進 apk 的,因此拿不到某個子目錄中單一資源的絕對路徑。
  2. 網路上常見的寫法 String filePath = "file:///android_asset/檔名"; 據說能表示檔案路徑,但實測不可靠,容易直接丟出例外。

正確做法是用 AssetManager 開啟串流,再交給 BitmapFactory 解碼。

MainActivity.java

package cc.testasset;

import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

/**
 * Demo 說明:獲取 asset 下的資源圖片
 */
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        // 測試一:讀取 asset 根目錄下的圖片
        try {
            AssetManager assetManager = getAssets();
            InputStream is = assetManager.open("Fresh_01.jpg");
            // 以下寫法不可靠,會丟例外:
            // InputStream is = assetManager.open("file:///android_asset/Fresh_01.jpg");
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            if (bitmap != null) {
                System.out.println("測試一:width=" + bitmap.getWidth()
                        + " ,height=" + bitmap.getHeight());
            } else {
                System.out.println("bitmap == null");
            }
        } catch (Exception e) {
            System.out.println("異常資訊:" + e.toString());
        }

        // 測試二:讀取 asset 子目錄中的圖片
        try {
            AssetManager assetManager = getAssets();
            InputStream is = assetManager.open("ml_lszn_Fresh/Fresh_02.jpg");
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            if (bitmap != null) {
                System.out.println("測試二:width=" + bitmap.getWidth()
                        + " ,height=" + bitmap.getHeight());
            }
        } catch (Exception e) {
            System.out.println("異常資訊:" + e.toString());
        }

        // 測試三:遍歷某子目錄下的所有圖片
        try {
            String dirPath = "ml_lszn_Fresh";
            AssetManager assetManager = getAssets();
            // 用 list() 取得該目錄下所有檔案名稱
            String[] photos = assetManager.list(dirPath);
            for (int i = 0; i < photos.length; i++) {
                // 用 dirPath + "/" + photoName 組出完整相對路徑
                InputStream is = assetManager.open(dirPath + "/" + photos[i]);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                System.out.println("測試三:i=" + i
                        + " ,width=" + bitmap.getWidth()
                        + " ,height=" + bitmap.getHeight());
            }
        } catch (Exception e) {
            System.out.println("異常資訊:" + e.toString());
        }
    }
}

三個測試分別示範:根目錄單檔、子目錄單檔、以及用 list() 搭配路徑拼接做批次讀取。

main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="獲取 asset 下的資源圖片" />
</RelativeLayout>

小結

assets 與 res/raw 的差別在於:assets 保留原始檔案結構與檔名,适合存放需要動態列舉的資源;res/raw 則會被系統分配資源 id,不能任意建立子目錄。若你的需求是「跑一張清單決定載入哪些圖」,assets 才是對的选择。另外記得,讀完的 InputStream 與 Bitmap 要適時關閉與回收,尤其在批次處理大量圖片時。

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