2022年 11月 5日

python 三种方式实现截屏(详解+完整代码)

一、方法一

# PIL中的ImageGrab模块
# 使用PIL中的ImageGrab模块简单,但是效率有点低
# PIL是Python Imaging Library,它为python解释器提供图像编辑函数能力。 ImageGrab模块可用于将屏幕或剪贴板的内容复制到PIL图像存储器中。
# PIL.ImageGrab.grab()方法拍摄屏幕快照。边框内的像素在Windows上以“RGB”图像的形式返回,在macOS上以“RGBA”的形式返回。
# 如果省略了边界框,则会复制整个屏幕。
  1. import numpy as np
  2. from PIL import ImageGrab, Image
  3. import cv2
  4. img = ImageGrab.grab(bbox=(0, 0, 1920, 1080)) # bbox 定义左、上、右和下像素的4元组
  5. print(img.size[1], img.size[0])
  6. img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3)
  7. print(img)
  8. cv2.imwrite('screenshot1.jpg', img)
  9. # img = Image.fromarray(img)
  10. # img.save('screenshot1.jpg')

二、方法二

# PyQt比调用windows API简单很多,而且有windows API的很多优势,比如速度快,可以指定获取的窗口,即使窗口被遮挡。
# 需注意的是,窗口最小化时无法获取截图。
# 首先需要获取窗口的句柄。
  1. import win32gui
  2. from PyQt5.QtWidgets import QApplication
  3. import sys
  4. hwnd_title = dict()
  5. def get_all_hwnd(hwnd, mouse):
  6. if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
  7. hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})
  8. win32gui.EnumWindows(get_all_hwnd, 0)
  9. # print(hwnd_title.items())
  10. for h, t in hwnd_title.items():
  11. if t != "":
  12. print(h, t)
  13. # 程序会打印窗口的hwnd和title,有了title就可以进行截图了。
  14. hwnd = win32gui.FindWindow(None, 'C:\Windows\system32\cmd.exe')
  15. app = QApplication(sys.argv)
  16. screen = QApplication.primaryScreen()
  17. img = screen.grabWindow(hwnd).toImage()
  18. img.save("screenshot2.jpg")

三、方法三

# pyautogui是比较简单的,但是不能指定获取程序的窗口,因此窗口也不能遮挡,不过可以指定截屏的位置
  1. import pyautogui
  2. import cv2 # https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv
  3. import numpy as np
  4. from PIL import Image
  5. img = pyautogui.screenshot(region=[0, 0, 1920, 1080]) # x,y,w,h
  6. # img = Image.fromarray(np.uint8(img))
  7. # img.save('screenshot3.png')
  8. img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) # cvtColor用于在图像中不同的色彩空间进行转换,用于后续处理。
  9. cv2.imwrite('screenshot3.jpg', img)