保存bmp文件中屏幕截图的设备上下文

时间:2016-12-03 22:40:00

标签: c++ windows

我有这个设备上下文,如何在不丢失原始RGB值的情况下以.bmp或其他格式保存?我有这个设备上下文,如何在不丢失原始RGB值的情况下以.bmp或其他格式保存? THX!

LPRGBQUAD hex_color;


//HDC dc = GetDC(NULL);

HWND hWnd = GetDesktopWindow();
HDC hdc = GetDC(hWnd);

RECT rect;
GetWindowRect(hWnd, &rect);

int MAX_WIDTH = rect.right - rect.left;
int MAX_HEIGHT = rect.bottom - rect.top;

//cout << "MAX_WIDTH " << MAX_WIDTH << " MAX_HEIGHT " << MAX_HEIGHT << endl;

HDC hdcTemp = CreateCompatibleDC(hdc);

BITMAPINFO bitmap;
bitmap.bmiHeader.biSize = sizeof(bitmap.bmiHeader);
bitmap.bmiHeader.biWidth = MAX_WIDTH;
bitmap.bmiHeader.biHeight = -MAX_HEIGHT;
bitmap.bmiHeader.biPlanes = 1;
bitmap.bmiHeader.biBitCount = 32;
bitmap.bmiHeader.biCompression = BI_RGB;
bitmap.bmiHeader.biSizeImage = 0;
bitmap.bmiHeader.biClrUsed = 0;
bitmap.bmiHeader.biClrImportant = 0;

LPRGBQUAD bitPointer;
HBITMAP hBitmap2 = CreateDIBSection(hdcTemp, &bitmap, DIB_RGB_COLORS, (void**)&bitPointer, 0, 0);

HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcTemp, hBitmap2);
BitBlt(hdcTemp, 0, 0, MAX_WIDTH, MAX_HEIGHT, hdc, 0, 0, SRCCOPY);

1 个答案:

答案 0 :(得分:1)

你需要比特的大小。对于32位图像,大小计算如下:

DWORD dib_size = MAX_WIDTH * MAX_HEIGHT * 4;

您还应将此值指定给bitmap.bmiHeader.biSizeImage

bitmap.bmiHeader.biSizeImage = dib_size;

接下来,您需要bmpFileHeader

BITMAPFILEHEADER bmpFileHeader = { 0 };
bmpFileHeader.bfType = 'MB';
bmpFileHeader.bfSize = 54 + dib_size;
bmpFileHeader.bfOffBits = 54;

bfType"BM"(小尾的向后),

bfSize54sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)

const wchar_t* filename = L"__unicode.bmp";
HANDLE hfile = CreateFileW(filename,
    GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hfile != INVALID_HANDLE_VALUE)
{
    DWORD temp;
    WriteFile(hfile, &bmpFileHeader, sizeof(BITMAPFILEHEADER), &temp, NULL);
    WriteFile(hfile, (BITMAPINFOHEADER*)&bitmap, sizeof(BITMAPINFOHEADER), &temp, NULL);
    WriteFile(hfile, bitPointer, dib_size, &temp, NULL);
    CloseHandle(hfile);
}

//release GDI resource handles
SelectObject(hdcTemp, hbmpOld);
DeleteObject(hBitmap2);
DeleteDC(hdcTemp);