简体   繁体   中英

How to load GDI::Image (GIF) from Resource in c++(winapi)?

I'm making a window c++ with winapi(non-MFC) and showing gif. For this Im using GDI++. I'm loading a gif to GDI::Image from the path, but I want to load it from resources. How can I do it?

    hMWDC = GetDC(hWnd);
    pGphcs = new Graphics(hMWDC);
    WCHAR path[MAX_PATH];
    GetModuleFileNameW(NULL, path, MAX_PATH);
    PathRemoveFileSpecW(path);
    PathAppendW(path, L"gifs\\test.gif");
    pImg = new Image(path);

    if (pImg) {
        nFrmCnt = pImg->GetFrameCount(&FrameDimensionTime);
        SetTimer(hWnd, DRAW_ANIM, 100, NULL);

    }
case WM_TIMER:
        if (wParam == DRAW_ANIM)
        {
            pImg->SelectActiveFrame(&FrameDimensionTime, nFrm);
            Rect DRC(0, 0, pImg->GetWidth(), pImg->GetHeight());
            pGphcs->Clear(Color(128, 128, 128));


            pGphcs->DrawImage(pImg, DRC);
            if (nFrm < (nFrmCnt - 1)) nFrm++; else nFrm = 0;
        }

        break;

There is an Image constructor that accepts an IStream*.

You can create a stream by calling SHCreateMemStream on the raw buffer of a resource, which can be obtained by calling FindResource / LoadResource / LockResource and SizeOfResource .

Add the GIF file to your app's resources at compile time. For instance, by compiling an .rc file similar to below into a .res file that you can then link into your executable (some compilers/IDEs have tools to automate this step):

Resources.rh

#define MY_GIF_ID 100

Resources.rc

#include "Resources.rh"
MY_GIF_ID RCDATA "gifs\\test.gif"

Then, you can obtain a pointer to the raw bytes of the resource at runtime.

#include "Resources.rh"

HMODULE hMod = GetModuleHandle(NULL);

HRSRC hRes = FindResource(hMod, MAKEINTRESOURCE(MY_GIF_ID), RT_RCDATA);
if (!hRes) { ... error handling ... } 

HGLOBAL hGlobal = LoadResource(hMod, hRes);
if (!hGlobal) { ... error handling ... } 

void *pResData = LockResource(hGlobal);
if (!pResData) { ... error handling ... } 

DWORD dwResData = SizeofResource(hMod, hRes);

See MSDN for more details:

Introduction to Resources

Finding and Loading Resources

And then finally, pass the resource bytes to the Image constructor that takes an IStream* as input:

#include <shlwapi.h>

IStream *pStream = SHCreateMemStream((BYTE*)pResData, dwResData);
if (!pStream) { ... error handling ... } 

pImg = new Image(pStream);
pStream->Release();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM