从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)
# ...
该更新已在 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