Python

Python 擷取螢幕畫面 pyscreenshot 模組使用教學與範例

介紹如何使用 Python 的 pyscreenshot 模組擷取螢幕畫面快照,適用於 Windows、Mac OS X 與 Linux 系統。

安裝 pyscreenshot 模組

pyscreenshot 是一個專門用來擷取螢幕畫面的 Python 模組,並將圖片轉為 PIL 或 Pillow 影像,可以做為 ImageGrab 模組的替代方案。

安裝 pyscreenshot 模組時,要連同 Pillow 模組一起安裝:

# 安裝 Pillow 與 pyscreenshot 模組
pip3 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")

擷取螢幕的區域是透過左上角的座標(X1Y1)與右下角的座標(X2Y2)來指定的,原點的位置位於整個螢幕的左上角,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")

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

Data to FishStackOverflowGeeksforGeeks

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago