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

Android 獲取螢幕截圖並儲存到 SD 卡

編輯:關於 Android 程式設計

以下程式碼示範如何獲取當前螢幕截圖,並將其儲存到 SD 卡指定路徑下。核心思路是:先建立 Bitmap,再透過 decorView 的 drawing cache 取得畫面,最後壓縮寫入檔案。

/**
 * 獲取並儲存當前螢幕截圖
 */
private void GetandSaveCurrentImage() {
    // 1. 建立 Bitmap
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    int w = display.getWidth();
    int h = display.getHeight();
    Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
    // 2. 獲取螢幕畫面
    View decorview = this.getWindow().getDecorView();
    decorview.setDrawingCacheEnabled(true);
    Bmp = decorview.getDrawingCache();
    String SavePath = getSDCardPath()+"/AndyDemo/ScreenImage";
    // 3. 儲存 Bitmap
    try {
        File path = new File(SavePath);
        String filepath = SavePath + "/Screen_1.png";
        File file = new File(filepath);
        if(!path.exists()){
            path.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = null;
        fos = new FileOutputStream(file);
        if (null != fos) {
            Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.flush();
            fos.close();
            Toast.makeText(this, "截圖已儲存至 SDCard/AndyDemo/ScreenImage/ 下", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 獲取 SD 卡目錄路徑
 */
private String getSDCardPath(){
    File sdcardDir = null;
    boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    if(sdcardExist){
        sdcardDir = Environment.getExternalStorageDirectory();
    }
    return sdcardDir.toString();
}

使用時需先確認 SD 卡已掛載,並在 AndroidManifest 中加入 WRITE_EXTERNAL_STORAGE 權限。

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