无需写入磁盘即可截取屏幕截图

ecl*_*pse 2 python byte screenshot python-mss

我想要一个python脚本,它可以在不立即将其直接保存到磁盘的情况下截取屏幕截图。基本上是否有一个带有函数的模块,该函数返回原始字节,然后我可以自己手动将其写入文件?

import some_screenshot_module
raw_data = some_screenshot_module.return_raw_screenshot_bytes()
f = open('screenshot.png','wb')
f.write(raw_data)
f.close()
Run Code Online (Sandbox Code Playgroud)

我已经检查了 mss、pyscreenshot 和 PIL,但我找不到我需要的东西。我找到了一个看起来像我要找的函数,叫做 frombytes。但是,在从 frombytes 函数检索字节并将其保存到文件中后,我无法将其视为 .BMP、.PNG、.JPG。是否有一个函数可以返回我可以自己保存到文件中的原始字节,或者可能是一个具有类似功能的模块?

Tig*_*222 5

MSS 3.1.2 开始,通过提交dd5298,您可以轻松地做到这一点:

import mss
import mss.tools


with mss.mss() as sct:
    # Use the 1st monitor
    monitor = sct.monitors[1]

    # Grab the picture
    im = sct.grab(monitor)

    # Get the entire PNG raw bytes
    raw_bytes = mss.tools.to_png(im.rgb, im.size)

    # ...
Run Code Online (Sandbox Code Playgroud)

该更新已经在 PyPi 上可用。


原答案

使用 MSS 模块,您可以访问原始字节:

import mss
import mss.tools


with mss.mss() as sct:
    # Use the 1st monitor
    monitor = sct.monitors[1]

    # Grab the picture
    im = sct.grab(monitor)

    # From now, you have access to different attributes like `rgb`
    # See https://python-mss.readthedocs.io/api.html#mss.tools.ScreenShot.rgb
    # `im.rgb` contains bytes of the screen shot in RGB _but_ you will have to
    # build the complete image because it does not set needed headers/structures
    # for PNG, JPEG or any picture format.
    # You can find the `to_png()` function that does this work for you,
    # you can create your own, just take inspiration here:
    # https://github.com/BoboTiG/python-mss/blob/master/mss/tools.py#L11

    # If you would use that function, it is dead simple:
    # args are (raw_data: bytes, (width, height): tuple, output: str)
    mss.tools.to_png(im.rgb, im.size, 'screenshot.png')
Run Code Online (Sandbox Code Playgroud)

另一个使用部分屏幕的例子:https : //python-mss.readthedocs.io/examples.html#part-of-the-screen

以下是更多信息的文档:https : //python-mss.readthedocs.io/api.html