在 Android 中,若要讀取打包在 Assets 目錄裡的圖片,可以透過 AssetManager 開啟檔案串流,再交給 BitmapFactory 解碼成 Bitmap。以下是一個可直接沿用的範例:
bgimg0 = getImageFromAssetsFile("Cat_Blink/cat_blink0000.png");
/**
* 從 Assets 中讀取圖片
*/
private Bitmap getImageFromAssetsFile(String fileName)
{
Bitmap image = null;
AssetManager am = getResources().getAssets();
try
{
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return image;
}
使用時只要傳入相對於 Assets 根目錄的路徑即可,例如子目錄中的檔案可寫成 "Cat_Blink/cat_blink0000.png"。若檔案不存在或讀取失敗,open 會丟出 IOException,因此別忘了以 try/catch 包覆並做好例外處理。