从资源加载图像并转换为内存中的位图

时间:2010-10-25 06:46:43

标签: c++ image resources bitmap

我使用谷歌搜索过但我完全不知道如何从资源加载图像(在我的情况下是PNG),然后将其转换为内存中的位图以便在我的启动画面中使用。我读过关于GDI +和libpng但我真的不知道怎么做我想要的。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

GDI +直接支持PNG。请参阅herehere

编辑: GDI+ documentation提供了有关如何在DLL中使用GDI +的一些建议。在您的情况下,最好的解决方案可能是定义客户端代码需要调用的初始化和拆卸功能。

答案 1 :(得分:0)

我最终使用PicoPNG将PNG转换为二维向量,然后我手动构造了一个位图。我的最终代码看起来像这样:

HBITMAP LoadPNGasBMP(const HMODULE hModule, const LPCTSTR lpPNGName)
{
    /* First we need to get an pointer to the PNG */
    HRSRC found = FindResource(hModule, lpPNGName, "PNG");
    unsigned int size = SizeofResource(hModule, found);
    HGLOBAL loaded = LoadResource(hModule, found);
    void* resource_data = LockResource(loaded);

    /* Now we decode the PNG */
    vector<unsigned char> raw;
    unsigned long width, height;
    int err = decodePNG(raw, width, height, (const unsigned char*)resource_data, size);
    if (err != 0)
    {
        log_debug("Error while decoding png splash: %d", err);
        return NULL;
    }

    /* Create the bitmap */
    BITMAPV5HEADER bmpheader = {0};
    bmpheader.bV5Size = sizeof(BITMAPV5HEADER);
    bmpheader.bV5Width = width;
    bmpheader.bV5Height = height;
    bmpheader.bV5Planes = 1;
    bmpheader.bV5BitCount = 32;
    bmpheader.bV5Compression = BI_BITFIELDS;
    bmpheader.bV5SizeImage = width*height*4;
    bmpheader.bV5RedMask = 0x00FF0000;
    bmpheader.bV5GreenMask = 0x0000FF00;
    bmpheader.bV5BlueMask = 0x000000FF;
    bmpheader.bV5AlphaMask = 0xFF000000;
    bmpheader.bV5CSType = LCS_WINDOWS_COLOR_SPACE;
    bmpheader.bV5Intent = LCS_GM_BUSINESS;
    void* converted = NULL;
    HDC screen = GetDC(NULL);
    HBITMAP result = CreateDIBSection(screen, reinterpret_cast<BITMAPINFO*>(&bmpheader), DIB_RGB_COLORS, &converted, NULL, 0);
    ReleaseDC(NULL, screen);

    /* Copy the decoded image into the bitmap in the correct order */
    for (unsigned int y1 = height - 1, y2 = 0; y2 < height; y1--, y2++)
        for (unsigned int x = 0; x < width; x++)
        {
            *((char*)converted+0+4*x+4*width*y2) = raw[2+4*x+4*width*y1]; // Blue
            *((char*)converted+1+4*x+4*width*y2) = raw[1+4*x+4*width*y1]; // Green
            *((char*)converted+2+4*x+4*width*y2) = raw[0+4*x+4*width*y1]; // Red
            *((char*)converted+3+4*x+4*width*y2) = raw[3+4*x+4*width*y1]; // Alpha
        }

    /* Done! */
    return result;
}