Michael C
Michael C

Reputation: 147

saving device context of a screen shot in a bmp file

I have this device context, how do I save it in a .bmp or another format without losing the original RGB values? I have this device context, how do I save it in a .bmp or another format without losing the original RGB values? 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);

Upvotes: 1

Views: 64

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31599

You need the size of bits. For 32bit image, the size is calculated as follows:

DWORD dib_size = MAX_WIDTH * MAX_HEIGHT * 4;

You should also assign this value to bitmap.bmiHeader.biSizeImage:

bitmap.bmiHeader.biSizeImage = dib_size;

Next, you need bmpFileHeader:

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

bfType is "BM" (backwards for little-endian),

bfSize is 54 which is sizeof(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);

Upvotes: 1

Related Questions