Win32 C/C++ 从内存缓冲区加载图像

2021-12-18 00:00:00 windows winapi c++ bitmap

我想在 Win32 应用程序上加载图像 (.bmp) 文件,但我不想使用 Windows API 中的标准 LoadBitmap/LoadImage:我希望它从内存中已有的缓冲区加载.我可以轻松地直接从文件加载位图并将其打印在屏幕上,但这个问题让我卡住了.

I want to load an image (.bmp) file on a Win32 application, but I do not want to use the standard LoadBitmap/LoadImage from Windows API: I want it to load from a buffer that is already in memory. I can easily load a bitmap directly from a file and print it on the screen, but this issue is making me stuck.

我正在寻找的是一个像这样工作的函数:

What I'm looking for is a function that works like this:

HBITMAP LoadBitmapFromBuffer(char* buffer, int width, int height);

推荐答案

没关系,我找到了我的解决方案!这是初始化代码:

Nevermind, I found my solution! Here's the initializing code:

std::ifstream is;
is.open("Image.bmp", std::ios::binary);
is.seekg (0, std::ios::end);
length = is.tellg();
is.seekg (0, std::ios::beg);
pBuffer = new char [length];
is.read (pBuffer,length);
is.close();

tagBITMAPFILEHEADER bfh = *(tagBITMAPFILEHEADER*)pBuffer;
tagBITMAPINFOHEADER bih = *(tagBITMAPINFOHEADER*)(pBuffer+sizeof(tagBITMAPFILEHEADER));
RGBQUAD             rgb = *(RGBQUAD*)(pBuffer+sizeof(tagBITMAPFILEHEADER)+sizeof(tagBITMAPINFOHEADER));

BITMAPINFO bi;
bi.bmiColors[0] = rgb;
bi.bmiHeader = bih;

char* pPixels = (pBuffer+bfh.bfOffBits);

char* ppvBits;

hBitmap = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**) &ppvBits, NULL, 0);
SetDIBits(NULL, hBitmap, 0, bih.biHeight, pPixels, &bi, DIB_RGB_COLORS);

GetObject(hBitmap, sizeof(BITMAP), &cBitmap);

相关文章