python可以获取特定窗口的屏幕快照吗?

Cuo*_*how 4 python

例如,我正在运行一个Java程序。我可以使用python获取此Java程序的内容(屏幕截图)吗?不是全屏显示,只是Java程序。

我已经看过这个模块,但是它需要一个参数“程序窗口在哪里”:

import pyscreenshot as ImageGrab

if __name__ == "__main__":
    # part of the screen
    im=ImageGrab.grab(bbox=(10,10,510,510)) # X1,Y1,X2,Y2
    im.show()
#-#
Run Code Online (Sandbox Code Playgroud)

但这可能不是我想要的,因为它需要bounding_box。

小智 8

借助模块获取特定窗口的内容(屏幕截图)的pygetwindow 示例

import pygetwindow
import time
import os
import pyautogui
import PIL

# get screensize
x,y = pyautogui.size()
print(f"width={x}\theight={y}")

x2,y2 = pyautogui.size()
x2,y2=int(str(x2)),int(str(y2))
print(x2//2)
print(y2//2)

# find new window title
z1 = pygetwindow.getAllTitles()
time.sleep(1)
print(len(z1))
# test with pictures folder
os.startfile("C:\\Users\\yourname\\Pictures")
time.sleep(1)
z2 = pygetwindow.getAllTitles()
print(len(z2))
time.sleep(1)
z3 = [x for x in z2 if x not in z1]
z3 = ''.join(z3)
time.sleep(3)

# also able to edit z3 to specified window-title string like: "Sublime Text (UNREGISTERED)"
my = pygetwindow.getWindowsWithTitle(z3)[0]
# quarter of screen screensize
x3 = x2 // 2
y3 = y2 // 2
my.resizeTo(x3,y3)
# top-left
my.moveTo(0, 0)
time.sleep(3)
my.activate()
time.sleep(1)

# save screenshot
p = pyautogui.screenshot()
p.save(r'C:\\Users\\yourname\\Pictures\\\\p.png')

# edit screenshot
im = PIL.Image.open('C:\\Users\\yourname\\Pictures\\p.png')
im_crop = im.crop((0, 0, x3, y3))
im_crop.save('C:\\Users\\yourname\\Pictures\\p.jpg', quality=100)

# close window
time.sleep(1)
my.close()
Run Code Online (Sandbox Code Playgroud)


alp*_*989 6

有多种方法可以做到这一点。这些代码需要根据您的需要进行修改,因此我将提供一些指向高级方法和库的指针:

  1. 您可以直接使用GUI自动化工具,例如PyautoguiAlt+ PrntScreen并将剪贴板中的数据传输到变量中(http://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys

  2. 您可以使用pywin32和PIL来获取特定窗口的图像(如何在Python 3k中获取窗口或全屏截图?(无PIL)

  3. 您可以使用imagemagik捕获单个窗口的屏幕截图(https://www.imagemagick.org/discourse-server/viewtopic.php?t=24702

  4. 您可以使用Pyautogui.locateOnScreen(“Sceenshot.PNG”) to find the tuple which will contain the boundaries of the window for your java app. Then you can pass it to your functionimg.ImageGrab.grab(bbox)`