screenshot.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from __future__ import annotations
  2. from abc import ABC, abstractmethod
  3. from pathlib import Path
  4. import numpy as np
  5. from PIL import ImageGrab
  6. _REPOSITORY_ROOT_DIRECTORY = Path(__file__).resolve().parent.parent
  7. _OUTPUT_SCREENSHOT_FILE_PATH = _REPOSITORY_ROOT_DIRECTORY / "output" / "screenshot.png"
  8. FULL_SCREEN_SCREENSHOT_OUTPUT_PNG_FILE_PATH: Path = _OUTPUT_SCREENSHOT_FILE_PATH
  9. current_full_screen_screenshot_bgr_numpy: np.ndarray | None = None
  10. class FullScreenScreenshotCaptureSaver(ABC):
  11. @abstractmethod
  12. def capture_full_screen_and_store_in_memory(self) -> np.ndarray:
  13. ...
  14. class PillowImageGrabFullScreenScreenshotCaptureSaver(FullScreenScreenshotCaptureSaver):
  15. def capture_full_screen_and_store_in_memory(self) -> np.ndarray:
  16. global current_full_screen_screenshot_bgr_numpy
  17. full_screen_rgba_image = ImageGrab.grab()
  18. full_screen_rgb_image = full_screen_rgba_image.convert("RGB")
  19. _OUTPUT_SCREENSHOT_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
  20. full_screen_rgb_image.save(_OUTPUT_SCREENSHOT_FILE_PATH, format="PNG")
  21. rgb_uint8_numpy = np.asarray(full_screen_rgb_image, dtype=np.uint8)
  22. bgr_uint8_numpy = rgb_uint8_numpy[:, :, ::-1].copy()
  23. current_full_screen_screenshot_bgr_numpy = bgr_uint8_numpy
  24. return bgr_uint8_numpy
  25. def capture_full_screen_screenshot_bgr_numpy_and_save_screenshot_png() -> np.ndarray:
  26. """全屏截图:写入 ``output/screenshot.png``(覆盖),并返回 BGR ``numpy``(与内存缓存一致)。"""
  27. full_screen_screenshot_capture_saver = PillowImageGrabFullScreenScreenshotCaptureSaver()
  28. return full_screen_screenshot_capture_saver.capture_full_screen_and_store_in_memory()