python - 使用 Python PIL 和 Windows API : how to deal with rounded corners? 的事件窗口屏幕截图

标签 python windows screenshot python-imaging-library rounded-corners

对于 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/

相关文章:

.net - Windows 10 上的 SQL Server 2014

three.js - webGL的WebGL单帧 "screenshot"

android - 将屏幕截图上传到 Google Play 时出错

python - 为什么在函数中返回抑制引发的异常?

python - Scrapy yield utf-8

python - 使用 mechanize 检索 robots.txt 时出现 HTTP 403 错误

html - HipChat URL 图片预览

python - 迭代 pandas 数据框中的行并应用 lambda 函数

linux - 单机上的多个操作系统

c++ - 在 AllocConsole 之前执行 std::endl 会导致不显示 std::cout