对于 this project ,我正在使用 Windows API 截取屏幕截图(以处理多屏幕)并将其转换为 PIL 图像;如果需要,我会在窗口周围添加阴影。
我的问题是,屏幕截图实际上是窗口的矩形;这意味着我在圆角周围捕捉它背后的背景,但我不想要那样。我在谷歌上搜索了很多,找到了关于透明度的文档和图,我猜我应该找到一种方法来获得窗口的形状,以便使其成为我将应用于我的(矩形)图像的蒙版得到。但我发现没办法拿到那个面具。有人能帮忙吗?
下面是我的代码:
hwnd = win32gui.GetForegroundWindow()
l, t, r, b = win32gui.GetWindowRect(hwnd)
w = r - l
h = b - t
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
#add cursor
if showcursor:
curFlags, curH, (curX, curY) = win32gui.GetCursorInfo()
saveDC.DrawIcon((curX, curY), curH)
#load into PIL image
"""http://stackoverflow.com/questions/4199497/image-frombuffer-with-16-bit-image-data"""
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(hwnd, hwndDC)
return im
下面是蓝色背景上方窗口的稍微放大的屏幕截图:
如您所见,有些蓝色角落不应该出现。
最佳答案
为什么不使用 Edge detection算法(例如 Prewitt 或 Sobel)来检测窗口边缘,您只需将 alpha channel 设置为图像范围和窗口边缘范围之间的像素。
关于python - 使用 Python PIL 和 Windows API : how to deal with rounded corners? 的事件窗口屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999007/