我試圖讓我的程序拍攝一張截圖,然後以這樣一種方式格式化數據,以便從我的程序中輕鬆操作。捕獲屏幕截圖
到目前爲止,我想出了以下解決方案:
/**
* Creates a screenshot of the entire screen
* @param img - 2d array containing RGB values of screen pixels.
*/
void get_screenshot(COLORREF** img, const Rectangle &bounds)
{
// get the screen DC
HDC hdc_screen = GetDC(NULL);
// memory DC so we don't have to constantly poll the screen DC
HDC hdc_memory = CreateCompatibleDC(hdc_screen);
// bitmap handle
HBITMAP hbitmap = CreateCompatibleBitmap(hdc_screen, bounds.width, bounds.height);
// select the bitmap handle
SelectObject(hdc_memory, hbitmap);
// paint onto the bitmap
BitBlt(hdc_memory, bounds.x, bounds.y, bounds.width, bounds.height, hdc_screen, bounds.x, bounds.y, SRCPAINT);
// release the screen DC
ReleaseDC(NULL, hdc_screen);
// get the pixel data from the bitmap handle and put it into a nice data structure
for(size_t i = bounds.x; i < bounds.x + bounds.width; ++i)
{
for(size_t j = bounds.y; j < bounds.y + bounds.height; ++j)
{
img[j-bounds.y][i-bounds.x] = GetPixel(hdc_memory, i, j);
}
}
// release our memory DC
ReleaseDC(NULL, hdc_memory);
}
*注:長方形其實是我與4個size_t
領域創造了左上角的X & y座標一個結構,而寬度和矩形的高度。它不是WinAPI矩形。
我對這個代碼的一些問題:
- 我是否正確釋放所有的資源呢?
- 有沒有更好的方法來做到這一點?我正在尋找一些具有相似級別的複雜性和靈活性的RGB值的二維數組。最終的屏幕捕獲數據處理將使用OpenCL完成,因此我寧願不要有任何複雜的結構。