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

把 Assets 裡的圖片讀出來存進 SD 卡

編輯:關於 Android 程式設計

有時候我們會把一批圖片放在 assets 目錄裡隨 APK 一起打包,執行時再依需要寫入外部儲存空間。這個流程拆開來其實只有三步:開啟檔案、逐段讀取位元組、解碼成 Bitmap 後存檔。

完整實作

public class ReadBitmap {

    /**
     * 依索引陣列中記錄的長度,逐張讀取 assets 中的圖片並存檔
     *
     * @param c        Context
     * @param name     assets 中的檔案名稱
     * @param indexInt 記錄每張圖片位元組長度的整數陣列資源 ID
     */
    public void readByte(Context c, String name, int indexInt) {
        byte[] b = null;
        int[] intArray = c.getResources().getIntArray(indexInt);
        try {
            AssetManager am = c.getAssets();
            InputStream is = am.open(name);
            for (int i = 0; i < intArray.length; i++) {
                b = new byte[intArray[i]];   // 依長度配置緩衝區
                is.read(b);                  // 讀取一段資料
                saveMyBitmap(Bytes2Bimap(b), MainActivity.DIR + name + i + ".jpg");
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 位元組陣列轉 Bitmap */
    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    /** 將 Bitmap 壓縮存檔 */
    public static boolean saveMyBitmap(Bitmap bmp, String path) {
        File f = new File(path);
        try {
            f.createNewFile();
            FileOutputStream fOut = new FileOutputStream(f);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

幾個環節說明

為什麼要預先記下每張圖的長度?這個寫法把多張圖片串接在同一個檔案裡,靠一份長度清單來切分。的好處是只需要開一次 InputStream,避開反覆開檔的成本;代價是 assets 裡得先備好對應的整數陣列資源,兩邊的順序與數值必須完全對得上。

decodeByteArray 而非 decodeFile:因為資料已經在記憶體裡,直接解位元組陣列最省事。反過來說,如果圖片很大,這種做法會同時佔用位元組陣列與 Bitmap 兩份記憶體,容易觸發 OOM。大圖建議改用 BitmapFactory.Options 搭配 inSampleSize 做降採樣。

compress 的品質參數:這裡傳 100 代表不壓縮品質,檔案會偏大。若只是要顯示用的縮圖,降到 80 上下通常肉眼無差,體積卻能少一半以上。

别忽略的權限與 API 差異

寫入外部儲存必須先聲明權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android 6.0 起這是危險權限,除了宣告還要在執行期動態向使用者申請;Android 10 之後又進一步引入分區儲存(Scoped Storage),預設情況下 App 只能自由存取自己專屬的目錄。

因此比較安穩的做法,是把存檔位置改為 getExternalFilesDir() 取得的 App 專屬路徑:

File dir = getExternalFilesDir(null);   // App 專屬,免申請權限
File target = new File(dir, name + i + ".jpg");

這個目錄在 App 解除安裝時會自動清除,不需要權限,也不受分區儲存限制。若確實需要存到使用者看得到的公開位置,則要改用 MediaStore API 來寫入。

最後,寫檔時建議把 createNewFile() 換成先 mkdirs() 確保父目錄存在,並在 finally 區塊中關閉串流,避免例外發生時檔案描述符洩漏。

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