在 Windows 上使用 python 截屏的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3586046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:50:19  来源:igfitidea点击:

Fastest way to take a screenshot with python on windows

pythonwindowsscreenshot

提问by Claudiu

What's the fastest way to take a screenshot on windows? PIL.ImageGrabis rather slow.. it takes between 4-5 seconds to take 30 screenshots of the same small window. Taking screenshots of the whole desktop is even slower.

在 Windows 上截取屏幕截图的最快方法是什么?PIL.ImageGrab相当慢.. 拍摄同一个小窗口的 30 个屏幕截图需要 4-5 秒。截取整个桌面的屏幕截图甚至更慢。

采纳答案by pyfunc

You could use win32 APIs directly .

您可以直接使用 win32 API。

1) First give the focus to the App that you want to take screenshot of. link text

1)首先将焦点放在您要截屏的应用程序上。 链接文字

2) Win32 APIcan help with the screenshot:

2) Win32 API可以帮助截图:

import win32gui
import win32ui 
hwnd = win32gui.FindWindow(None, windowname)
wDC = win32gui.GetWindowDC(hwnd)
dcObj=win32ui.CreateDCFromHandle(wDC)
cDC=dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
dataBitMap.SaveBitmapFile(cDC, bmpfilenamename)
# Free Resources
dcObj.DeleteDC()
cDC.DeleteDC()
win32gui.ReleaseDC(hwnd, wDC)
win32gui.DeleteObject(dataBitMap.GetHandle())

回答by Claudiu

Just found out how to do it with gtk. Seems fastest by far:

刚刚发现如何用 gtk 做到这一点。到目前为止似乎最快:

def image_grab_gtk(window):
    left, top, right, bot = get_rect(window)
    w = right - left
    h = bot - top

    s = gtk.gdk.Pixbuf(
        gtk.gdk.COLORSPACE_RGB, False, 8, w, h)

    s.get_from_drawable(
        gtk.gdk.get_default_root_window(),
        gtk.gdk.colormap_get_system(),
        left, top, 0, 0, w, h )

    final = Image.frombuffer(
        "RGB",
        (w, h),
        s.get_pixels(),
        "raw",
        "RGB",
        s.get_rowstride(), 1)
    return final

Without converting to a PILImage, it's 8x faster than PIL on my test case. With converting, it's still ~2.7x faster.

在不转换为PIL图像的情况下,它在我的测试用例中比 PIL 快 8 倍。通过转换,它仍然快约 2.7 倍。