MFC實現螢幕截圖
阿新 • • 發佈:2021-08-28
螢幕截圖
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); } }