TShopping

標題: Python 擷取螢幕畫面 pyscreenshot 模組使用教學與範例 [打印本頁]

作者: woff    時間: 2020-12-29 18:19
標題: Python 擷取螢幕畫面 pyscreenshot 模組使用教學與範例
介紹如何使用 Python 的 pyscreenshot 模組擷取螢幕畫面快照,適用於 Windows、Mac OS X 與 Linux 系統。

安裝 pyscreenshot 模組
pyscreenshot 是一個專門用來擷取螢幕畫面的 Python 模組,並將圖片轉為 PIL 或 Pillow 影像,可以做為 ImageGrab 模組的替代方案。
安裝 pyscreenshot 模組時,要連同 Pillow 模組一起安裝:
  1. # 安裝 Pillow 與 pyscreenshot 模組
  2. pip install Pillow pyscreenshot
複製代碼

擷取全螢幕畫面
使用 pyscreenshot 模組擷取全螢幕的畫面:
  1. import pyscreenshot as ImageGrab

  2. # 擷取全螢幕畫面
  3. image = ImageGrab.grab()

  4. # 儲存檔案
  5. image.save("fullscreen.png")
複製代碼



擷取指定區域螢幕畫面
  1. import pyscreenshot as ImageGrab

  2. # 擷取指定範圍畫面(影像大小為 500x500 像素)
  3. im = ImageGrab.grab(
  4.   bbox=(20,   # X1
  5.         20,   # Y1
  6.        520,   # X2
  7.        520))  # Y2

  8. # 儲存檔案
  9. im.save("box.png")
複製代碼

擷取螢幕的區域是透過左上角的座標(X1 與 Y1)與右下角的座標(X2 與 Y2)來指定的,原點的位置位於整個螢幕的左上角,X 軸的方向是由上往下遞增,Y 軸則是由左至右遞增。

虛擬幀緩衝區畫面(無螢幕伺服器)
在 Linux 伺服器亦可使用 Xvfb 來建立虛擬幀緩衝區,再以 pyscreenshot 擷取應用程式的畫面:
  1. from time import sleep
  2. from easyprocess import EasyProcess
  3. from pyvirtualdisplay import Display
  4. import pyscreenshot as ImageGrab

  5. with Display(size=(100, 60)) as disp:  # 開啟 Xvfb 虛擬幀緩衝區
  6.     # 執行 xmessage 程式,顯示於虛擬幀緩衝區
  7.     with EasyProcess(["xmessage", "hello"]):
  8.         sleep(1)               # 等待畫面顯示
  9.         img = ImageGrab.grab() # 擷取螢幕畫面

  10. # 儲存檔案
  11. img.save("xmessage.png")
複製代碼

除了使用 pyscreenshot 模組之外,類似功能的 Python 模組還有 mss 模組、wx 模組、ImageGrab 模組等。


文章出處
網頁設計,網站架設 ,網路行銷,網頁優化,SEO - NetYea 網頁設計






歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2