• 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 +如何从资源获取和加载图像?

  • 相关阅读:
    git push要输入密码问题
    excel换行
    React的diff算法
    https的通信过程
    一道面试题的分析
    Mac将应用拖入Finder工具栏
    React获取组件实例
    Warning: Received `false` for a non-boolean attribute `xxx`.
    warning: React does not recognize the xxx prop on a DOM element
    webpack开发模式和生产模式设置及不同环境脚本执行
  • 原文地址:https://www.cnblogs.com/strive-sun/p/14409594.html
Copyright © 2020-2023  润新知