在 C++ 中将向量 <unsigned char> 转换为 HBITMAP

Convert vector <unsigned char> to HBITMAP in C++

我已经使用代码 here 将 PNG 图像加载到 BMP 原始矢量 std::vector <unsigned char>。现在,我需要将此图像作为背景应用到 WinAPI window,但我不知道如何将其转换为 HBITMAP。也许有人以前做过或者我可以使用另一种格式或变量类型

您可以从一开始就使用 Gdiplus 打开 png 文件并获得 HBITMAP 句柄

//initialize Gdiplus:
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

HBITMAP hbitmap;
HBRUSH hbrush;

Gdiplus::Bitmap *bmp = Gdiplus::Bitmap::FromFile(L"filename.png");
bmp->GetHBITMAP(0, &hbitmap);
hbrush = CreatePatternBrush(hbitmap);

//register classname and assign background brush
WNDCLASSEX wcex;
...
wcex.hbrBackground = hbrush;

CreateWindow...

清理:

DeleteObject(hbrush);
DeleteObject(hbitmap);

delete bmp;

Gdiplus::GdiplusShutdown(gdiplusToken);

您需要将 "gdiplus.h" 和 link 添加到 "gdiplus.lib" 库中。头文件应该默认可用。

在Visual Studio你可以link到Gdiplus如下:

#pragma comment( lib, "Gdiplus.lib")


编辑

或在WM_PAINT

中使用Gdiplus::Image
Gdiplus::Image *image = Gdiplus::Image::FromFile(L"filename.png");

WM_PAINT 在 Window 过程中:

case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);

    if (image)
    {
        RECT rc;
        GetClientRect(hwnd, &rc);
        Gdiplus::Graphics g(hdc);
        g.DrawImage(image, Gdiplus::Rect(0, 0, rc.right, rc.bottom));
    }

    EndPaint(hwnd, &ps);
    return 0;
}