前言
最近在研究windows截屏的功能。
窗口截图(HWND)
-
PrintWindow 参考代码
-
QT的grabWindow 参考代码
-
winapi.BitBlt 参考代码
以上方法都无法抓取以下类的app图片(来自obs代码):
-
chrome
-
Mozilla
-
XLMAIN /*excel */
-
PPTFrameClass /* powerpoint* /
-
OpusApp /* word */
-
ApplicationFrameWindow
-
windows.UI.Core.CoreWindow
而只能采用“桌面截图”的方式
桌面截图
- pyautogui.screenshot
- ImageGrab.grab
网上查找资料:
windows 窗口采集
里面有详细的桌面截图介绍。
最终采用的方式
如果操作系统 > win10 1903 版本,就使用wgc 方式;
否则采用BitBlt;
对于BitBlt 也无法截图的窗口,则采用桌面截屏。
WGC使用方法
Windows Graphics Capture(wgc)窗口采集的dll库 链接封装了使用dll库。
需要设置抓图的窗口即可回调数据。
struct ST_IMAGE
{
int width; //图片宽
int height; //图片高
int bits; //单像素bits数,这里固定图像格式为 B8G8R8A8(bgra = 32bits)
int rowPitch; //每行像素的bytes数 = width*bits/8
int slicePitch; //整幅图像的bytes数 = rowPitch*height
unsigned char* pixels; //Pointer to the system memory buffer for the pixel data
};
/**
* @brief 图像回调。
*
* 注意: stImage.pixels 的内存数据只读,不可修改。如要特殊处理,请copy
*/
typedef void (STDCALL *image_CallBack_PF)(ST_IMAGE stImage,void* pUser);
/*
* @brief 初始化,必须,不可重复调用 ,win_hwnd=NULL 内部创建显示窗口,!=NULL 使用外部窗口
* auth 授权码,未授权受限0.25帧/s;授权后可达60帧/s。 获取授权码,可email: 86122114@qq.com
*/
EXPORT_API int STDCALL wgclib_init(void* win_hwnd,char* auth);
/*
* @brief 设置抓拍的窗口句柄
*/
EXPORT_API void STDCALL wgclib_capture_hwnd(void* hwnd,image_CallBack_PF pFunc,void *pUser);
如何保存灰度图片
在代码SimpleCapture.cpp 中增加成员函数:
static uint8_t *s_pix = nullptr;
static int s_slicePitch = 0;
void TakeSnapshot(ST_IMAGE stImage,void* pUser)
{
ST_IMAGE copy_im = {0};
// 图片格式BGRA8,变灰度图
{
int pix = stImage.bits;
copy_im.rowPitch = stImage.width*pix;
copy_im.slicePitch = stImage.rowPitch*stImage.height;
if(s_slicePitch != copy_im.slicePitch)
{
if(s_pix)
{
delete []s_pix;
s_pix = nullptr;
}
s_pix = new uint8_t[copy_im.slicePitch];
s_slicePitch = copy_im.slicePitch;
}
copy_im.pixels = s_pix;
for(int i = 0,j = 0;i < copy_im.slicePitch;i++)
{
uint8_t b = stImage.pixels[j];
uint8_t g = stImage.pixels[j+1];
uint8_t r = stImage.pixels[j+2];
copy_im.pixels[i] = b;
j = j+4;
}
static int file_index = 0;
wchar_t buff[260] = {0};
swprintf(buff,260,L"output_%d.jpg",file_index);
//save2jpg(copy_im );
file_index++;
}
}
## PrintWindow 和 BitBlt
[https://worktile.com/kb/p/6009](https://worktile.com/kb/p/6009)