File size: 1,658 Bytes
4585960 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | """Fast cross-platform screen capture using mss (desktop) or PIL fallback (headless)."""
import numpy as np
from PIL import Image
def capture_primary_monitor() -> Image.Image:
"""Capture the primary monitor and return a PIL RGB Image."""
try:
import mss
with mss.mss() as sct:
monitor = sct.monitors[1] # primary monitor
screenshot = sct.grab(monitor)
img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
return img
except Exception:
# Fallback for headless/server environments
img = Image.new("RGB", (1280, 720), color=(30, 30, 46))
return img
def capture_all_monitors() -> Image.Image:
"""Capture all monitors combined."""
try:
import mss
with mss.mss() as sct:
monitor = sct.monitors[0] # all monitors
screenshot = sct.grab(monitor)
img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
return img
except Exception:
img = Image.new("RGB", (1280, 720), color=(30, 30, 46))
return img
def capture_region(top: int, left: int, width: int, height: int) -> Image.Image:
"""Capture a specific region."""
try:
import mss
with mss.mss() as sct:
region = {"top": top, "left": left, "width": width, "height": height}
screenshot = sct.grab(region)
img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
return img
except Exception:
img = Image.new("RGB", (width, height), color=(30, 30, 46))
return img
|