Reprint explains 4 ways to take screenshots in Python

This article was last updated on: February 7, 2024 pm

Python screenshot method

Today, I will share with you a detailed explanation of the 4 ways to get screenshots in Python, which has good reference value, and I hope it will be helpful to you.

Python can get screenshots of computers in several ways, as follows:

  • PIL ImageGrab module
  • windows API
  • PyQt
  • pyautogui

PIL ImageGrab module

1
2
3
4
5
6
7
import time
import numpy as np
from PIL import ImageGrab

img = ImageGrab.grab(bbox=(100, 161, 1141, 610))
img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3)

Use PIL ImageGrab The module is simple, but the efficiency is a bit low, and it takes 0.5s to take a screenshot.

windows API

Calling Windows APIs is fast but more complicated to use, so I won’t go into detail here, because there are better PyQt to use.

PyQt

PyQt is much simpler than calling the windows API and has many advantages of the Windows API, such as speed, and the ability to specify the window to get, even if the window is occluded. It should be noted that screenshots cannot be obtained when the window is minimized.

You first need to get a handle to the window.

1
2
3
4
5
6
7
8
9
10
11
12
import win32gui
hwnd_title = dict()
def get_all_hwnd(hwnd,mouse):
if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})

win32gui.EnumWindows(get_all_hwnd, 0)

for h,t in hwnd_title.items():
if t is not "":
print(h, t)

The program prints the window’s hwnd and titlepregnant title You can take a screenshot.

1
2
3
4
5
6
7
8
9
10
11
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import win32gui
import sys

hwnd = win32gui.FindWindow(None, 'C:\Windows\system32\cmd.exe')
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img = screen.grabWindow(hwnd).toImage()
img.save("screenshot.jpg")

pyautogui

pyautogui It is relatively simple, but you can’t specify the window to get the program, so the window can’t be occluded, but you can specify the location of the screenshot, 0.04s a screenshot, slightly slower than PyQt, but also fast.

1
2
3
4
5
6
7
import pyautogui
import cv2

img = pyautogui.screenshot(region=[0,0,100,100]) # x,y,w,h
# img.save('screenshot.png')
img = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)

📑Original:

4 Ways to Get Screenshots in Python_Python_Script House (jb51.net)

Modify Date: 2019-08-27 15:33:08 Author: Sunji\


Reprint explains 4 ways to take screenshots in Python
https://e-whisper.com/posts/43874/
Author
east4ming
Posted on
September 27, 2021
Licensed under