[英]Capturing screenshots with win32api python returns black image
我使用以下代碼示例來捕獲屏幕截圖:
https://stackoverflow.com/a/3260811 https://stackoverflow.com/a/24352388/5858697
截取 Firefox 或 chrome 的屏幕截圖時,它們會返回一個空白的黑色圖像。 捕獲記事本的屏幕截圖工作正常。 我對此進行了一些研究,我認為這是因為它們是 gpu 加速的。 其他屏幕截圖庫可以工作,但我需要它,以便我可以捕獲應用程序的屏幕截圖,即使它當前不可見。
有沒有人解決過類似的問題,或者有人能指出我正確的方向嗎? 謝謝你。
根據@Barmak 之前的回答,我將 C++ 代碼轉換為 python,現在它可以工作了。
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 使用Windowless Controls 。
如果您想獲得 Firefox 的句柄,您可能需要UI Automation 。
有關詳細說明,請參閱@IInspectable 的回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.