Assets 目錄適合存放隨應用打包的唯讀資源(字體、預置圖片、資料庫模板)。本文示範如何讀取 Assets 圖片、解碼為 Bitmap、寫入外部儲存。
public class AssetBitmapSaver {
public void saveAssetsImages(Context context, String assetName, int[] sizeArray) {
AssetManager am = context.getAssets();
try (InputStream is = am.open(assetName)) {
for (int i = 0; i < sizeArray.length; i++) {
byte[] buffer = new byte[sizeArray[i]];
int read = is.read(buffer);
if (read <= 0) break;
Bitmap bitmap = bytesToBitmap(buffer);
String outPath = Environment.getExternalStorageDirectory()
+ File.separator + assetName + i + ".jpg";
saveBitmap(bitmap, outPath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap bytesToBitmap(byte[] data) {
return (data.length > 0) ? BitmapFactory.decodeByteArray(data, 0, data.length) : null;
}
private boolean saveBitmap(Bitmap bmp, String path) {
File file = new File(path);
try {
file.createNewFile();
try (FileOutputStream fos = new FileOutputStream(file)) {
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
// res/values/arrays.xml 定義每張圖預期位元組數(可略過,改用 available() 讀取全串流)
<integer-array name="asset_img_sizes">
<item>102400</item>
<item>204800</item>
</integer-array>
// Activity 中呼叫
int[] sizes = getResources().getIntArray(R.array.asset_img_sizes);
new AssetBitmapSaver().saveAssetsImages(this, "preload_photo.jpg", sizes);
BufferedInputStream 分塊讀取並直接 BitmapFactory.decodeStream;<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>(API 29+ 改用 MediaStore/Scoped Storage);IntentService、WorkManager 或協程避免阻塞 UI 執行緒;OutOfMemoryError、磁碟空間不足、權限拒絕等異常並上報。