【问题标题】:Can python get the screen shot of a specific window?python可以获取特定窗口的屏幕截图吗?
【发布时间】:2016-11-25 17:06:58
【问题描述】:

例如,我正在运行一个 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()
#-#

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

【问题讨论】:

  • 你可以检测你想要捕获的窗口并找到它的高度、宽度和坐标...
  • @MooingRawr 感谢您的想法。但是怎么做?我原本以为可能有一种方法可以提供窗口标题或程序ID

标签: python


【解决方案1】:

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

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

  2. 可以使用pywin32和PIL抓取某个窗口的图片(How to Get a Window or Fullscreen Screenshot in Python 3k? (without 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)`

【讨论】:

    【解决方案2】:

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

    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()
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多