使用 win32api python 捕获屏幕截图返回黑色图像 [英] Capturing screenshots with win32api python returns black image

查看:260
本文介绍了使用 win32api python 捕获屏幕截图返回黑色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码示例来捕获屏幕截图:

I've used the following code examples to capture a screenshot:

https://stackoverflow.com/a/3260811https://stackoverflow.com/a/24352388/5858697

截取 Firefox 或 chrome 的屏幕截图时,它们返回一个空白的黑色图像.捕获记事本的屏幕截图工作正常.我对此进行了一些研究,我认为这是因为它们是 gpu 加速的.其他屏幕截图库也可以使用,但我需要使用它,以便我可以捕获应用程序的屏幕截图,即使它当前不可见.

When taking a screenshot of Firefox or chrome, they return a blank black image. Capturing a screenshot of notepad works fine. I've done some research on this and I think it's because they're gpu accelerated. Other screenshot libraries work but I need to have it so I can capture a screenshot of an application even if it's not currently visible.

有没有人解决过类似的问题,或者有人能指出我正确的方向吗?谢谢.

Has anyone solved a similar problem or could someone point me in the right direction? Thank you.

推荐答案

基于 @Barmak 之前的回答,我将 C++ 代码转换为 python,现在可以运行了.

Based on the @Barmak's previous answer, I converted C + + code to python, and now it works.

import win32gui
import win32ui
import win32con
from ctypes import windll
from PIL import Image
import time
import ctypes

hwnd_target = 0x00480362 #Chrome handle be used for test 

left, top, right, bot = win32gui.GetWindowRect(hwnd_target)
w = right - left
h = bot - top

win32gui.SetForegroundWindow(hwnd_target)
time.sleep(1.0)

hdesktop = win32gui.GetDesktopWindow()
hwndDC = win32gui.GetWindowDC(hdesktop)
mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()

saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

saveDC.SelectObject(saveBitMap)

result = saveDC.BitBlt((0, 0), (w, h), mfcDC, (left, top), win32con.SRCCOPY)

bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)

im = Image.frombuffer(
    'RGB',
    (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
    bmpstr, 'raw', 'BGRX', 0, 1)

win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hdesktop, hwndDC)

if result == None:
    #PrintWindow Succeeded
    im.save("test.png")

请注意:Firefox 使用无窗口控件.

Please note: Firefox uses Windowless Controls.

如果您想获得 Firefox 的句柄,您可能需要 UI 自动化.

If you want to get the handle of Firefox, you may need UI Automation.

详细解释请参考@IInspectable的回答.

这篇关于使用 win32api python 捕获屏幕截图返回黑色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆