截取屏幕截图而不写入磁盘

Take screenshot without writing to disk

我想要一个 python 脚本,可以截取屏幕截图而无需立即将其直接保存到磁盘。基本上有没有一个模块具有 returns 原始字节的功能,然后我可以自己手动将其写入文件?

import some_screenshot_module
raw_data = some_screenshot_module.return_raw_screenshot_bytes()
f = open('screenshot.png','wb')
f.write(raw_data)
f.close()

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

您仍然可以使用带有 grab_to_file 函数的 pyscreenshot 模块和 PIL,只需使用命名管道而不是实际文件。

如果您在 linux 上,您可以使用 os.mkfifo 创建管道,然后打开 fifo 以在一个线程中读取并让 pyscreenshot.grab_to_file 在另一个线程中调用(它必须是不同的线程,因为打开 fifo 进行写入块,直到另一个线程打开它进行读取,反之亦然)

这是一个可行的代码片段:

import os
import multiprocessing
import pyscreenshot

fifo_name = "/tmp/fifo.png"


def read_from_fifo(file_name):
    f = open(file_name,"rb")
    print f.read()
    f.close()

os.mkfifo(fifo_name)
proc = multiprocessing.Process(target=read_from_fifo, args=(fifo_name,))
proc.start()

pyscreenshot.grab_to_file(fifo_name)

在这种情况下,我只是将原始字节打印到屏幕上,但你可以用它做任何你想做的事

另请注意,即使内容从未写入磁盘,磁盘上也有一个临时文件,但数据从未缓冲在其中

MSS 3.1.2, with the commit 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)

    # ...

更新已在 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')

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

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