MFC实现屏幕截屏

屏幕截屏

void CMainFormDlg::GetScreenPic(Rect area, OUT Mat &img, float rate, bool gray) {

	CDC *pDC = GetDesktopWindow()->GetDC();//屏幕DC
	int BitPerPixel = pDC->GetDeviceCaps(BITSPIXEL);//获得颜色模式
	int Width = MIN(pDC->GetDeviceCaps(HORZRES), area.width);
	int Height = MIN(pDC->GetDeviceCaps(VERTRES), area.height);


	CDC memDC;//内存DC
	memDC.CreateCompatibleDC(pDC);

	CBitmap memBitmap, *oldmemBitmap;//建立和屏幕兼容的bitmap
	memBitmap.CreateCompatibleBitmap(pDC, Width, Height);

	oldmemBitmap = memDC.SelectObject(&memBitmap);//将memBitmap选入内存DC
	memDC.BitBlt(0, 0, Width, Height, pDC, area.x, area.y, SRCCOPY);//复制屏幕图像到内存DC

	BITMAP bmp;
	memBitmap.GetBitmap(&bmp);//获得位图信息
	BITMAPINFOHEADER bih = { 0 };//位图信息头
	bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小
	bih.biCompression = BI_RGB;
	bih.biHeight = bmp.bmHeight;//高度
	bih.biPlanes = 1;
	bih.biSize = sizeof(BITMAPINFOHEADER);
	bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小
	bih.biWidth = bmp.bmWidth;//宽度

	BITMAPFILEHEADER bfh = { 0 };//位图文件头
	bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
	bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小
	bfh.bfType = (WORD)0x4d42;

	//Mat(nHeight, nWidth, CV_8UC1, pImageData).copyTo(CCDImage[0]);
	byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据
	GetDIBits(memDC.m_hDC, (HBITMAP)memBitmap.m_hObject, 0, Height, p, (LPBITMAPINFO)&bih, DIB_RGB_COLORS);//获取位图数据

	Mat temp;
	flip(Mat(Height, Width, CV_8UC4, p), temp, 0);
	delete[] p;

	memDC.SelectObject(oldmemBitmap);
	memDC.DeleteDC();
	ReleaseDC(pDC);

	if (gray) {
		cvtColor(temp, temp, CV_BGRA2GRAY);
		resize(temp, img, Size(), rate, rate);
	} else {
		cvtColor(temp, temp, CV_BGRA2BGR);
		resize(temp, img, Size(), rate, rate);
	}
}

原文地址:https://www.cnblogs.com/Abraverman/p/15200199.html