gpt4 book ai didi

c++ - 在 bmp 文件中保存屏幕截图的设备上下文

转载 作者:行者123 更新时间:2023-11-30 05:19:52 24 4
gpt4 key购买 nike

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

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);

最佳答案

您需要位的大小。对于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);

关于c++ - 在 bmp 文件中保存屏幕截图的设备上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com