# 获取窗口位置 left, top, right, bottom = win32gui.GetWindowRect(hwnd) # 获取窗口坐标 width = right - left height = bottom - top hwndDC = win32gui.GetWindowDC(hwnd) # 获取窗口DC mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, width, height) saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY) # 获取位图信息 bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) # 转换为numpy数组 img = np.frombuffer(bmpstr, dtype='uint8') img.shape = (bmpinfo['bmHeight'], bmpinfo['bmWidth'], 4) cv2.imwrite('1.bmp', img) return bmpstr 可以优化吗
时间: 2024-02-14 21:15:56 浏览: 220
这段代码可以优化,主要是针对截图和保存图像的部分。下面是优化后的代码:
```python
import win32gui
import win32ui
import win32con
import numpy as np
def get_screenshot(hwnd):
# 获取窗口位置
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
width = right - left
height = bottom - top
# 创建DC对象
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
# 创建位图对象
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)
# 将位图选入DC对象
saveDC.SelectObject(saveBitMap)
# 截屏
saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY)
# 获取位图数据
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
# 将位图数据转换为numpy数组
img = np.frombuffer(bmpstr, dtype='uint8')
img.shape = (bmpinfo['bmHeight'], bmpinfo['bmWidth'], 4)
# 释放资源
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
# 返回截屏结果
return img
```
优化后的代码增加了释放资源的部分,并且使用更加简洁的方式来截屏和保存图像。你可以尝试使用优化后的代码,看看是否可以满足你的需求。
阅读全文