python-mss API详解:掌握grab()与monitors()的终极用法

【免费下载链接】python-mss An ultra fast cross-platform multiple screenshots module in pure Python using ctypes. 【免费下载链接】python-mss 项目地址: https://gitcode.com/gh_mirrors/py/python-mss

python-mss是一个超快速的跨平台多屏幕截图模块,采用纯Python编写并使用ctypes。它为开发者提供了简单而强大的API,帮助轻松实现屏幕捕获功能。本文将详细解析其核心API——grab()与monitors()的终极用法,让你快速掌握屏幕截图的精髓。

一、认识MSSBase类:API的核心基础

MSSBase类是python-mss的基础抽象类,定义了所有屏幕截图实现的核心接口。所有平台相关的实现都继承自此类,确保了跨平台API的一致性。该类位于src/mss/base.py文件中,是理解整个API的关键。

核心属性与初始化

创建MSS实例时可配置多个参数:

  • compression_level: PNG压缩级别(默认6)
  • with_cursor: 是否包含鼠标光标(默认False)
  • display: X11显示名称(仅GNU/Linux)
  • max_displays: 最大显示器数量(仅macOS)

基本初始化示例:

with mss.mss() as sct:
    # 在此使用sct对象进行截图操作

二、monitors()方法:获取显示器信息

方法定义与功能

monitors()方法用于获取所有显示器的位置和属性信息,定义如下:

@property
def monitors(self) -> Monitors:
    """Get positions of all monitors."""

返回值结构

该方法返回一个Monitors对象(本质是列表),其中:

  • monitors[0]: 包含所有显示器组合的虚拟屏幕信息
  • monitors[N]: 第N个显示器的信息(N>0)

每个显示器信息是一个字典,包含:

  • left: 左上角x坐标
  • top: 左上角y坐标
  • width: 宽度
  • height: 高度
  • is_primary: 是否为主显示器(可选)
  • name: 设备名称(可选)
  • unique_id: 平台特定标识符(可选)

使用示例

获取所有显示器信息:

with mss.mss() as sct:
    monitors = sct.monitors
    print(f"检测到{len(monitors)-1}个显示器")
    for i, monitor in enumerate(monitors[1:], 1):
        print(f"显示器{i}: {monitor['width']}x{monitor['height']}")

主显示器访问

MSSBase还提供了primary_monitor属性快速获取主显示器:

primary = sct.primary_monitor
print(f"主显示器: {primary['width']}x{primary['height']}")

三、grab()方法:捕获屏幕区域

方法定义与功能

grab()方法是截图的核心功能,用于捕获指定区域的屏幕内容,定义如下:

def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:
    """Retrieve screen pixels for a given monitor."""

参数说明

该方法接受两种类型的参数:

  1. Monitor对象:通过monitors()方法获取的显示器信息
  2. 元组:(left, top, right, bottom),类似PIL.ImageGrab.grab的参数格式

返回值

返回一个ScreenShot对象,包含以下主要属性:

  • rgb: RGB格式的像素数据
  • size: 截图尺寸(宽, 高)
  • pos: 截图位置(x, y)
  • raw: 原始像素数据

使用示例

1. 捕获整个主显示器
with mss.mss() as sct:
    primary = sct.primary_monitor
    screenshot = sct.grab(primary)
    # 保存为PNG
    mss.tools.to_png(screenshot.rgb, screenshot.size, output='screenshot.png')
2. 捕获指定区域
with mss.mss() as sct:
    # 捕获(100, 100)到(500, 500)的区域
    region = (100, 100, 500, 500)
    screenshot = sct.grab(region)
3. 捕获特定显示器
with mss.mss() as sct:
    # 捕获第二个显示器
    if len(sct.monitors) > 2:
        screenshot = sct.grab(sct.monitors[2])

四、高级用法与最佳实践

1. 批量截图

使用save()方法可以方便地批量捕获和保存多个显示器的截图:

with mss.mss() as sct:
    # 捕获所有显示器并保存
    for filename in sct.save(output='monitor-{mon}.png'):
        print(f"保存截图: {filename}")

2. 高效连续截图

对于需要连续截图的场景(如屏幕录制),建议重用MSS对象以提高性能:

with mss.mss() as sct:
    monitor = sct.primary_monitor
    for _ in range(10):  # 捕获10张截图
        sct.grab(monitor)

3. 包含鼠标光标

初始化时设置with_cursor=True可以捕获鼠标光标:

with mss.mss(with_cursor=True) as sct:
    screenshot = sct.grab(sct.primary_monitor)

五、错误处理与注意事项

常见异常

  • ScreenShotError: 截图操作失败时抛出,如无效的区域大小
  • IndexError: 访问不存在的显示器时抛出

错误处理示例

from mss.exception import ScreenShotError

try:
    with mss.mss() as sct:
        if len(sct.monitors) < 2:
            raise ScreenShotError("未检测到显示器")
        screenshot = sct.grab(sct.monitors[1])
except ScreenShotError as e:
    print(f"截图错误: {e}")

性能提示

  • 避免在循环中反复创建MSS对象
  • 对于频繁截图,考虑使用较低的压缩级别
  • 只捕获需要的区域,而非整个屏幕

六、实际应用示例

1. 简单屏幕捕获工具

import mss
import mss.tools

def capture_screen(output='screenshot.png'):
    with mss.mss() as sct:
        # 捕获主显示器
        monitor = sct.primary_monitor
        screenshot = sct.grab(monitor)
        # 保存为PNG
        mss.tools.to_png(screenshot.rgb, screenshot.size, output=output)
    print(f"截图已保存至 {output}")

if __name__ == "__main__":
    capture_screen()

2. 多显示器信息检测工具

import mss

def list_monitors():
    with mss.mss() as sct:
        print(f"检测到 {len(sct.monitors)-1} 个显示器:")
        for i, monitor in enumerate(sct.monitors[1:], 1):
            is_primary = " (主显示器)" if monitor.get('is_primary', False) else ""
            print(f"显示器 {i}{is_primary}:")
            print(f"  分辨率: {monitor['width']}x{monitor['height']}")
            print(f"  位置: ({monitor['left']}, {monitor['top']})")

if __name__ == "__main__":
    list_monitors()

七、总结

python-mss的grab()和monitors()方法提供了强大而灵活的屏幕截图能力。通过monitors()方法可以轻松获取系统显示器信息,而grab()方法则能高效捕获指定区域的屏幕内容。无论是简单的截图工具还是复杂的屏幕录制应用,python-mss都能满足你的需求。

要开始使用python-mss,只需通过以下命令安装:

pip install mss

然后克隆仓库获取完整示例:

git clone https://gitcode.com/gh_mirrors/py/python-mss

探索docs/source/examples/目录下的示例代码,你可以发现更多高级用法和最佳实践。掌握这些API,让你的屏幕截图功能开发变得简单而高效!

【免费下载链接】python-mss An ultra fast cross-platform multiple screenshots module in pure Python using ctypes. 【免费下载链接】python-mss 项目地址: https://gitcode.com/gh_mirrors/py/python-mss

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐