扣丁书屋

DLL图片资源加载到内存中

3年以前  |  阅读数:40 次  |    

头文件(.h)

class CResourceImage
{
public:
    CResourceImage();
    ~CResourceImage();

    BOOL LoadImage( HMODULE hModule, const WCHAR * lpName, const WCHAR * lpType );

    int GetWidth();
    int GetHeight();

    void Draw(HDC hDC, int x, int y, int cx, int cy, int x_src, int y_src, int cx_src, int cy_src);

private:
    HGLOBAL m_hGlobal;
    Bitmap* m_pBitmap;
};

#endif

实现文件(.cpp)

CResourceImage::CResourceImage() : m_hGlobal(NULL),m_pBitmap(NULL)
{

}

CResourceImage::~CResourceImage()
{

}

int CResourceImage::GetWidth()
{
    if (m_pBitmap)
    {
        return m_pBitmap->GetWidth();
    }
    return 0;
}

int CResourceImage::GetHeight()
{
    if (m_pBitmap)
    {
        return m_pBitmap->GetHeight();
    }
    return 0;
}

void CResourceImage::Draw(HDC hDC, int x, int y, int cx, int cy, int x_src, int y_src, int cx_src, int cy_src)
{
    if (m_pBitmap)
    {
        Graphics g(hDC);
        g.DrawImage(m_pBitmap,RectF(x, y, cx, cy),x_src,y_src,cx_src,cy_src, UnitPixel);
    }
}

BOOL CResourceImage::LoadImage( HMODULE hModule, const WCHAR * lpName, const WCHAR * lpType )
{
    CResReader sResReader;
    sResReader.LoadResource(hModule, lpName, lpType);

    if(sResReader.GetData() == NULL) return FALSE;
    if(sResReader.GetDataSize() <= 0) return FALSE;

    BOOL bSuccess = TRUE;
    do 
    {
        if (m_hGlobal)
        {
            GlobalFree(m_hGlobal);
            m_hGlobal = NULL;
        }

        if (m_pBitmap)
        {
            delete m_pBitmap;
            m_pBitmap = NULL;
        }

        bSuccess = FALSE;

        //分配文件长度大小的内存块
        m_hGlobal = ::GlobalAlloc (GPTR, sResReader.GetDataSize());
        if (m_hGlobal == NULL) break;

        //将文件数据读入内存块
        void* pBuffer = (void*)m_hGlobal;
        memcpy(pBuffer, sResReader.GetData(), sResReader.GetDataSize());

        //在内存块上创建流
        IStream* pStream = NULL;
        bSuccess = SUCCEEDED (::CreateStreamOnHGlobal (m_hGlobal, TRUE, &pStream));
        if(bSuccess && pStream)
        {
            m_pBitmap = new Bitmap(pStream, FALSE);  
            if (!m_pBitmap || m_pBitmap->GetLastStatus() != Ok)
            {
                delete m_pBitmap;
            }
        }
    } while (FALSE);

    return TRUE;
}

相关文章: