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

將 Bitmap 以 PNG 格式保存到內部存儲的方法

編輯:關於 Android 程式設計

在 Android 中進行圖像處理時,我們常常希望把處理後的結果以圖片檔案的形式保存到內部存儲中。本文就來介紹如何將 Bitmap 物件的資料以 PNG 格式保存下來。

1、添加權限

由於涉及對存儲的讀寫操作,首先必須為程式添加相應權限:

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

這兩個權限的含義分別是:

"android.permission.MOUNT_UNMOUNT_FILESYSTEMS" --> 允許掛載與反掛載可移動存儲
"android.permission.WRITE_EXTERNAL_STORAGE" --> 在 sdcard 中創建檔案的權限

2、保存圖片的相關程式碼

程式碼並不複雜,這裡直接使用絕對路徑,你也可以透過 Environment 取得不同位置的標準路徑。

小提示:呼叫時記得把檔案副檔名帶上。

private void saveBitmap(Bitmap bitmap, String bitName) throws IOException {
    File file = new File("/sdcard/DCIM/Camera/" + bitName);
    if (file.exists()) {
        file.delete();
    }
    FileOutputStream out;
    try {
        out = new FileOutputStream(file);
        if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
            out.flush();
            out.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

補充:Bitmap 保存為檔案的原理

Bitmap 類有一個 compress 成員方法,可以把 bitmap 保存到一個 stream 中。例如:

public void saveMyBitmap(String bitName) throws IOException {
    File f = new File("/sdcard/Note/" + bitName + ".png");
    f.createNewFile();
    FileOutputStream fOut = null;
    try {
        fOut = new FileOutputStream(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    try {
        fOut.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

其中 compress 的第二個參數為壓縮品質(0–100),PNG 為無損格式,通常傳 100 即可。以上就是把 Bitmap 保存為 PNG 圖片的完整做法,希望對你有所幫助。

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