本文摘自php中文网,作者尚,侵删。

Python获取电脑截图有多种方式,具体如下:
PIL中的ImageGrab模块
windows API
PyQt
pyautogui
PIL中的ImageGrab模块
1 2 3 4 5 6 | 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)
|
使用PIL中的ImageGrab模块简单,但是效率有点低。
windows API
调用windows API,速度快但是使用较复杂,这里就不做详细介绍了,因为有更好用的PyQt。
PyQt
PyQt比调用windows API简单很多,而且有windows API的很多优势,比如速度快,可以指定获取的窗口,即使窗口被遮挡。需注意的是,窗口最小化时无法获取截图。
首先需要获取窗口的句柄。
1 2 3 4 5 6 7 8 9 10 11 | 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)
|
程序会打印窗口的hwnd和title,有了title就可以进行截图了。
1 2 3 4 5 6 7 8 9 10 | 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是比较简单的,但是不能指定获取程序的窗口,因此窗口也不能遮挡,不过可以指定截屏的位置,0.04s一张截图,比PyQt稍慢一点,但也很快了。
1 2 3 4 5 6 | 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)
|
更多Python相关技术文章,请访问Python教程栏目进行学习!
以上就是python如何进行截图的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python语言采用严格的什么
Python如何爬取网页中js添加的内容 (代码)
Python可以做游戏开发吗
Python读取文件内容的三种方式与效率比较的详解
Python中logging的详细介绍(附示例)
Python获取程序执行文件路径的方法
Python中int函数是什么意思
Python怎么去掉最后的空格
Python如何计算平均值
Python swapcase函数有什么用
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何进行截图