我试图让我的程序拍摄一张截图,然后以这样一种方式格式化数据,以便从我的程序中轻松操作。捕获屏幕截图
到目前为止,我想出了以下解决方案:
/**
* 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完成,因此我宁愿不要有任何复杂的结构。