例如,我正在运行一个java程序。我可以使用python来获取这个java程序的内容(截图)吗?不是全屏,只是java程序。
我见过这个模块,但它需要一个参数“程序窗口在哪里”:
nil
但这可能不是我所寻求的,因为它需要bounding_box。
答案 0 :(得分:3)
有多种方法可以做到这一点。这些代码需要根据您的需要进行修改,因此我将提供一些指向高级方法和库的指针:
您可以直接使用Pyautogui
等GUI自动化工具按Alt
+ PrntScreen
并将数据从剪贴板传输到变量(http://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys)
您可以使用pywin32和PIL来抓取某个窗口的图像(How to Get a Window or Fullscreen Screenshot in Python 3k? (without PIL))
您可以使用imagemagik抓取单个窗口的屏幕截图(https://www.imagemagick.org/discourse-server/viewtopic.php?t=24702)
您可以使用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 function
img.ImageGrab.grab(bbox)`
答案 1 :(得分:1)
获取特定窗口内容(屏幕截图)的示例。
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()