首页 > 解决方案 > Convert LPVOID bitmap pointer to QPixmap

问题描述

I am trying to load in a BMP image from a resources folder into a QPixmap object. However, I can't read the bytes even though rewriting those bytes to a new file makes a correct copy of the original. Here is my loading method:

QPixmap* GUIMain::loadImage(int name) {
    // Resource loading, works fine
    HRSRC rc = FindResource(NULL, MAKEINTRESOURCE(name), RT_BITMAP);

    if (rc == NULL) {
        printf("INVALID RESOURCE ADDRESS (%i)\n", name);
        return new QPixmap();
    }

    HGLOBAL rcData = LoadResource(NULL, rc);
    LPVOID data = LockResource(rcData);
    DWORD data_size = SizeofResource(NULL, rc);

    // Rewrite file to new file, works fine
    ofstream output("E:\\" + to_string(name) + ".bmp", std::ios::binary);
    BITMAPFILEHEADER bfh = { 'MB', 54 + data_size, 0, 0, 54 };
    output.write((char*)&bfh, sizeof(bfh));
    output.write((char*)data, data_size);
    output.close();

    // Need to return, can't get bytes working
    return new QPixmap(/*?*/);
}

This method is called with the definitions from the resource.h file.

I have tried to use a stringstream with the same calls as the ofstream, followed by using that stream as a source for the QPixmap, but the stream didn't produce the same output.

Here are the relevant parts of my resource.h file:

#define IDB_BITMAP1                     101
#define IDB_BITMAP2                     102

Here is my Resource.rc file:

IDB_BITMAP1             BITMAP                  "E:\\Downloads\\onIcon.bmp"

IDB_BITMAP2             BITMAP                  "E:\\Downloads\\offIcon.bmp"

I know I should be using the Qt tools for resource management, but I don't have the capabilities to do so.

标签: c++qtembedded-resource

解决方案


您可以使用 QPixmap::loadFromData(...) 从 bmp 格式的字节创建 QPixmap,但您也不需要在 .rc 文件中将资源声明为“BITMAP”。

位图资源旨在与LoadBitmap(...)LoadImage(...)一起使用,并存储在 .exe 中,并去掉位图标头。(Raymond Chen 在这里讨论这个)由于您没有使用 LoadBitmap 将资源的类型设置为任意二进制数据,例如

IDB_BITMAP1 RCDATA "E:\\Downloads\\onIcon.bmp"

然后实现您的图像加载例程,如下所示:

QPixmap* GUIMain::loadImage(int name) {

    // ...

    HGLOBAL rcData = LoadResource(NULL, rc);
    LPVOID data = LockResource(rcData);
    DWORD data_size = SizeofResource(NULL, rc);

    QPixmap* pm = new QPixmap();
    pm->loadFromData( static_cast<uchar*>(data), data_size, "bmp");

    return pm;
}

推荐阅读