用Python拍摄的截图完全是黑色的

问题描述 投票:0回答:1

所以我有这个代码:

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

hwnd = win32gui.FindWindow(None, "#chat - Discord")

# Change the line below depending on whether you want the whole window
# or just the client area. 
left, top, right, bot = win32gui.GetClientRect(hwnd)
#left, top, right, bot = win32gui.GetWindowRect(hwnd)
w = right - left
h = bot - top

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

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

saveDC.SelectObject(saveBitMap)

# Change the line below depending on whether you want the whole window
# or just the client area. 
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
#result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)


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

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

if result:
    #PrintWindow Succeeded
    im.show()

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

问题在于它所采用的截图全是黑色的。它适用于所有窗口,而不仅仅是Discord。它有什么问题,我需要做些什么来解决它?

另外作为一个侧面问题 - 当我截取屏幕截图时,命令提示符打开然后快速关闭,是否还有一种方法可以阻止这种情况发生?

python win32gui
1个回答
0
投票

问题在于它所采用的截图全是黑色的。

我知道你想拍一张截图吗?

from PIL.ImageGrab import grab
image = grab()
image.save('Screenshot.png')

如果您有窗口的坐标,请尝试以下方法:

from PIL.ImageGrab import grab
box = (0,0,200,200)
image = grab(box)
image.save('Screenshot.png')

PIL已经停止使用,因此您可能只能在下一个不久的将来使用此代码。此外,此代码不显示命令提示符。

© www.soinside.com 2019 - 2024. All rights reserved.