介紹如何使用 Python 的 pyscreenshot 模組擷取螢幕畫面快照,適用於 Windows、Mac OS X 與 Linux 系統。
安裝 pyscreenshot 模組安裝 pyscreenshot 模組時,要連同 Pillow 模組一起安裝: - # 安裝 Pillow 與 pyscreenshot 模組
- pip install Pillow pyscreenshot
複製代碼
擷取全螢幕畫面使用 pyscreenshot 模組擷取全螢幕的畫面: - import pyscreenshot as ImageGrab
- # 擷取全螢幕畫面
- image = ImageGrab.grab()
- # 儲存檔案
- image.save("fullscreen.png")
複製代碼
擷取指定區域螢幕畫面- import pyscreenshot as ImageGrab
- # 擷取指定範圍畫面(影像大小為 500x500 像素)
- im = ImageGrab.grab(
- bbox=(20, # X1
- 20, # Y1
- 520, # X2
- 520)) # Y2
- # 儲存檔案
- im.save("box.png")
複製代碼
擷取螢幕的區域是透過左上角的座標(X1 與 Y1)與右下角的座標(X2 與 Y2)來指定的,原點的位置位於整個螢幕的左上角,X 軸的方向是由上往下遞增,Y 軸則是由左至右遞增。
虛擬幀緩衝區畫面(無螢幕伺服器)在 Linux 伺服器亦可使用 Xvfb 來建立虛擬幀緩衝區,再以 pyscreenshot 擷取應用程式的畫面: - from time import sleep
- from easyprocess import EasyProcess
- from pyvirtualdisplay import Display
- import pyscreenshot as ImageGrab
- with Display(size=(100, 60)) as disp: # 開啟 Xvfb 虛擬幀緩衝區
- # 執行 xmessage 程式,顯示於虛擬幀緩衝區
- with EasyProcess(["xmessage", "hello"]):
- sleep(1) # 等待畫面顯示
- img = ImageGrab.grab() # 擷取螢幕畫面
- # 儲存檔案
- img.save("xmessage.png")
複製代碼
文章出處
網頁設計,網站架設 ,網路行銷,網頁優化,SEO - NetYea 網頁設計
|