在进行 Windows UI 自动化或 RPA 开发时,"截图"是一项非常高频的操作,它不仅用于生成测试报告、保存错误日志,更是实现图像识别(如图色定位、FindImageOnScreen)的核心基础。
在 winuia-auto 库中,截图方式丰富多样。本文将带你全面盘点 winuia-auto 的几大核心截图函数:ToBitmap、Screenshot 和 CaptureToImage,并区分控件级截图 与桌面级截图的正确打开方式。
一、 核心截图函数大盘点
| 方法 | 截图范围 | 返回值 | 是否支持离屏 | 典型用途 |
|---|---|---|---|---|
ToBitmap(x, y, w, h) |
控件指定区域 | Bitmap 对象 | 取决于实现 | 内存处理、找图 |
ToBitmap() |
整个控件 | Bitmap 对象 | 取决于实现 | 整窗转 Bitmap |
CaptureToImage(...) |
控件指定区域 | 直接保存文件 | 一般不支持 | 快速保存局部图 |
Screenshot(path, offscreen=True) |
整个控件 | 直接保存文件 | 支持 | 整窗截图(含隐藏) |
root.ToBitmap(...) |
桌面指定区域 | Bitmap 对象 | - | 屏幕级截图 |
FindImageOnScreen(...) |
- | 匹配结果 | - | 截图后做图像识别 |
二、实际应用
import winuia as auto
# 定义截图区域坐标
left, top, width, height = 100, 100, 400, 300
# 控件界面截图
window2 = auto.WindowControl(ClassName='Chrome_WidgetWin_1', RegexName='.*Google Chrome')
# 将控件截图指定区域并转成Bitmap
bitmap = window2.ToBitmap(left, top, width, height)
# 保存截图
window2.CaptureToImage(r'./region.png', left+width, top, width, height)
# 将控件截图保存成文件
window2.Screenshot("./control.png", offscreen=True)
# 将控件截图并转成Bitmap
bitmap = window2.ToBitmap()
# 桌面截图
root = auto.GetRootControl()
bitmap = root.ToBitmap(left, top, width, height)
# 验证截图, 将 Bitmap 转换为 PNG 格式的字节流,并用于屏幕找图验证
match_result1 = auto.FindImageOnScreen(bytes(bitmap.ToBytes('png')), confidence=0.85)
print(f'match_result1: {match_result1}')
# 保存截图
root.CaptureToImage(r'./region.png', left+width, top, width, height)
# 将桌面截图保存成文件
root.Screenshot("./control.png", offscreen=True)