zoukankan      html  css  js  c++  java
  • win32

    很多时候我们习惯使用GDI+中Image类来加载本地文件,但是有时候我们需要资源中从加载png格式的图片时,却无法使用该类。

    我们可以使用FindResourceLoadResourceLockResource以获取指向图像字节的指针。然后从中创建一个IStream。IStream可用于初始化GDI +图像或位图对象。

    在.rc文件中添加新行:

    IDI_MY_IMAGE_FILE    PNG      "foo.png"
    

    并确保在resource.h头文件中将IDI_MY_IMAGE_FILE定义为整数。

    #define IDI_MY_IMAGE_FILE         131

    然后在运行时加载图像:

    Gdiplus::Bitmap* pBmp = LoadImageFromResource(hInstance, MAKEINTRESOURCE(IDI_MY_IMAGE_FILE), L"PNG");
    

    LoadImageFromResource的代码如下:

    Gdiplus::Bitmap* LoadImageFromResource(HMODULE hMod, const wchar_t* resid, const wchar_t* restype)
    {
        IStream* pStream = nullptr;
        Gdiplus::Bitmap* pBmp = nullptr;
        HGLOBAL hGlobal = nullptr;
    
        HRSRC hrsrc = FindResourceW(hInst, resid, restype);     // get the handle to the resource
        if (hrsrc)
        {
            DWORD dwResourceSize = SizeofResource(hMod, hrsrc);
            if (dwResourceSize > 0)
            {
                HGLOBAL hGlobalResource = LoadResource(hMod, hrsrc); // load it
                if (hGlobalResource)
                {
                    void* imagebytes = LockResource(hGlobalResource); // get a pointer to the file bytes
    
                    // copy image bytes into a real hglobal memory handle
                    hGlobal = ::GlobalAlloc(GHND, dwResourceSize);
                    if (hGlobal)
                    {
                        void* pBuffer = ::GlobalLock(hGlobal);
                        if (pBuffer)
                        {
                            memcpy(pBuffer, imagebytes, dwResourceSize);
                            HRESULT hr = CreateStreamOnHGlobal(hGlobal, TRUE, &pStream);
                            if (SUCCEEDED(hr))
                            {
                                // pStream now owns the global handle and will invoke GlobalFree on release
                                hGlobal = nullptr;
                                pBmp = new Gdiplus::Bitmap(pStream);
                            }
                        }
                    }
                }
            }
        }
    
        if (pStream)
        {
            pStream->Release();
            pStream = nullptr;
        }
    
        if (hGlobal)
        {
            GlobalFree(hGlobal);
        }
    
        return pBmp;
    }

    相关链接: C ++ GDI +如何从资源获取和加载图像?

  • 相关阅读:
    全球疫情可视化
    ListView(1)
    《浪潮之巅》阅读笔记02
    Intern Day12
    Intern Day11
    Intern Day10
    Intern Day10
    Intern Day10
    PTA1065
    Intern Day10
  • 原文地址:https://www.cnblogs.com/strive-sun/p/14409594.html
Copyright © 2011-2022 走看看