使用 Python 的 mss 库获取窗口图片的方法

mss (Multiple Screen Shots) 是一个快速、跨平台的屏幕截图库,相比 PIL/Pillow 的截图功能,它速度更快且更高效。下面我将介绍如何使用 mss 获取特定窗口的图片。

图片[1]_使用 Python 的 mss 库获取窗口图片的方法_知途无界

基本安装

首先安装 mss 库:

pip install mss

方法一:获取全屏或屏幕区域截图

虽然 mss 不能直接通过窗口句柄获取窗口截图,但可以通过获取屏幕特定区域的截图来间接实现。

1. 获取全屏截图

import mss
import mss.tools

with mss.mss() as sct:
    # 获取第一个显示器的全屏截图
    monitor = sct.monitors[1]  # monitors[0] 是所有显示器的虚拟合并,monitors[1] 是第一个显示器
    
    screenshot = sct.grab(monitor)
    
    # 保存为PNG文件
    mss.tools.to_png(screenshot.rgb, screenshot.size, output="fullscreen.png")
    print("全屏截图已保存为 fullscreen.png")

2. 获取屏幕特定区域截图

import mss
import mss.tools

with mss.mss() as sct:
    # 定义要截取的区域 (left, top, width, height)
    # 例如:左上角(100, 100),宽400,高300的矩形区域
    region = {"left": 100, "top": 100, "width": 400, "height": 300}
    
    screenshot = sct.grab(region)
    
    # 保存为PNG文件
    mss.tools.to_png(screenshot.rgb, screenshot.size, output="region.png")
    print("区域截图已保存为 region.png")

方法二:获取特定窗口截图(需要结合其他库)

mss 本身不能直接通过窗口标题或句柄获取窗口截图,但你可以结合 pygetwindow(跨平台)或 win32gui(Windows专用)等库先获取窗口位置和大小,再用 mss 截取该区域。

Windows平台:使用 win32gui 获取窗口位置(推荐用于精确窗口截图)

import mss
import mss.tools
import win32gui

def get_window_rect(window_title):
    """通过窗口标题获取窗口的位置和大小"""
    hwnd = win32gui.FindWindow(None, window_title)
    if hwnd == 0:
        raise Exception(f"未找到标题为 '{window_title}' 的窗口")
    
    # 获取窗口矩形
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    width = right - left
    height = bottom - top
    
    # 如果只想截取客户区(不含标题栏等),可以使用 GetClientRect + ClientToScreen
    # 但 GetWindowRect 已经包含整个窗口(包括边框和标题栏)
    return {"left": left, "top": top, "width": width, "height": height}

# 替换为你要截取的窗口标题(必须是窗口的完整或部分可见标题)
window_title = "记事本"  # 例如:记事本、Google Chrome 等

try:
    window_region = get_window_rect(window_title)
    
    with mss.mss() as sct:
        screenshot = sct.grab(window_region)
        mss.tools.to_png(screenshot.rgb, screenshot.size, output=f"{window_title}_screenshot.png")
        print(f"窗口 '{window_title}' 的截图已保存为 {window_title}_screenshot.png")
except Exception as e:
    print(f"错误: {e}")

跨平台方案:使用 pygetwindow(功能有限)

import mss
import mss.tools
import pygetwindow as gw

def get_window_region(window_title):
    """通过窗口标题获取窗口位置(跨平台,但可能不够精确)"""
    windows = gw.getWindowsWithTitle(window_title)
    if not windows:
        raise Exception(f"未找到标题包含 '{window_title}' 的窗口")
    
    win = windows[0]  # 取第一个匹配的窗口
    return {"left": win.left, "top": win.top, "width": win.width, "height": win.height}

window_title = "Untitled - Notepad"  # 根据实际情况修改窗口标题

try:
    region = get_window_region(window_title)
    
    with mss.mss() as sct:
        screenshot = sct.grab(region)
        mss.tools.to_png(screenshot.rgb, screenshot.size, output=f"{window_title}_screenshot.png")
        print(f"窗口 '{window_title}' 的截图已保存为 {window_title}_screenshot.png")
except Exception as e:
    print(f"错误: {e}")

注意​:

  • pygetwindow 在 Linux 和 macOS 上的支持可能有限,且获取的窗口位置有时不够精确。
  • win32gui 是 Windows 专用,但能更准确地获取窗口位置,推荐在 Windows 上使用。

方法三:获取所有显示器信息

你可以先查看所有显示器的信息,以确定要截取的区域:

import mss

with mss.mss() as sct:
    for i, monitor in enumerate(sct.monitors[1:], 1):  # 从1开始,跳过虚拟合并的monitors[0]
        print(f"显示器 {i}: {monitor}")

输出示例:

显示器 1: {'left': 0, 'top': 0, 'width': 1920, 'height': 1080, 'monitors': 1, 'top_monitor': 1}

这样你可以根据显示器的分辨率设定要截取的窗口区域。

总结

方法适用场景是否需要额外库精确度
mss 直接截取屏幕区域已知窗口大致位置,截取屏幕特定区域仅 mss中等
mss + win32gui(Windows)精确获取特定窗口截图mss + pywin32
mss + pygetwindow(跨平台)跨平台获取窗口截图(精度一般)mss + pygetwindow中等

推荐方案:​

  • 如果你只需要截取屏幕的某个区域,使用 mss 直接指定区域即可。
  • 如果你需要精确截取某个窗口(尤其是 Windows),推荐使用 mss + win32gui 组合,先获取窗口位置再截取。
  • 如果你需要跨平台支持,可以尝试 mss + pygetwindow,但对窗口位置的精确度可能不如 Windows 上的 win32gui

希望这些方法能帮助你使用 Python 和 mss 库有效地获取窗口或屏幕截图!

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞89 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容