Home>Article>Backend Development> How to take screenshot in python

How to take screenshot in python

尚
Original
2019-06-29 15:05:31 7829browse

How to take screenshot in python

There are many ways to obtain computer screenshots in Python, as follows:

ImageGrab module in PIL

windows API

PyQt

pyautogui

ImageGrab module in PIL

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)

Using the ImageGrab module in PIL is simple, but the efficiency is a bit low.

windows API

Call the windows API, which is fast but complicated to use. I won’t go into details here because there is PyQt, which is better to use.

PyQt

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

First you need to get the handle of the window.

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 will print the hwnd and title of the window. With the title, you can take a screenshot.

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 is relatively simple, but you cannot specify the window to obtain the program, so the window cannot be blocked, but you can specify the location of the screenshot. A screenshot takes 0.04s, which is slightly faster than PyQt. Slower, but faster.

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)

For more Python-related technical articles, please visit thePython Tutorialcolumn to learn!

The above is the detailed content of How to take screenshot in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn