How to load .png , .jpeg images using MFC?

2020-01-30 07:12发布

Hi i want to load png images and jpeg images.

can anyone help me?

7条回答
【Aperson】
2楼-- · 2020-01-30 07:41
//----- load png into CImage from resource
bool Load( CImage * pimage, LPCTSTR lpszResourceName, HINSTANCE hinstRes)
{
    if (hinstRes == NULL)
    {
        hinstRes = AfxFindResourceHandle(lpszResourceName, _T("PNG") );
    }

    HRSRC hRsrc = ::FindResource(hinstRes, lpszResourceName, _T("PNG") );
    if (hRsrc == NULL)
    {
        return false;
    }

    HGLOBAL hGlobal = LoadResource(hinstRes, hRsrc);
    if (hGlobal == NULL)
    {
        return false;
    }

    LPBYTE lpBuffer = (LPBYTE) ::LockResource(hGlobal);
    if (lpBuffer == NULL)
    {
        FreeResource(hGlobal);
        return false;
    }

    bool bRes = false;
    {
        UINT uiSize = ::SizeofResource(hinstRes, hRsrc);

        HGLOBAL hRes = ::GlobalAlloc(GMEM_MOVEABLE, uiSize);
        if (hRes != NULL)
        {
            IStream* pStream = NULL;
            LPVOID lpResBuffer = ::GlobalLock(hRes);
            ASSERT (lpResBuffer != NULL);

            memcpy(lpResBuffer, lpBuffer, uiSize);

            HRESULT hResult = ::CreateStreamOnHGlobal(hRes, TRUE, &pStream);

            if( hResult == S_OK)
            {
                pimage->Load(pStream);
                pStream->Release();
                bRes= true;
            }
        }
    }

    UnlockResource(hGlobal);
    FreeResource(hGlobal);

    return bRes;
}
查看更多
做个烂人
3楼-- · 2020-01-30 07:43

For PNGs that come from resources

CPngImage pngImage;
pngImage.Load(YOUR_RESOURCE_ID, AfxGetResourceHandle());
CBitmap bitmap;
bitmap.Attach(pngImage.Detach());

will make you happy. bitmap can also be added to an CImageList.

查看更多
一纸荒年 Trace。
4楼-- · 2020-01-30 07:48

There is a simple CPngImage in the MFC. It is derived from CBitmap and allows to load a PNG as a CBitmap.

AFAIK this class is available since VS-2010.

查看更多
劫难
5楼-- · 2020-01-30 07:49

You can use CImage class which supports the following formats: JPEG, GIF, BMP, and PNG.

http://msdn.microsoft.com/en-us/library/bwea7by5%28VS.80%29.aspx

Use Load function to load file from disk:

http://msdn.microsoft.com/en-us/library/tf4bytf8%28VS.80%29.aspx

查看更多
一纸荒年 Trace。
6楼-- · 2020-01-30 07:52
CImage image;
image.Load(_T("C:\\image.png")); // just change extension to load jpg
CBitmap bitmap;
bitmap.Attach(image.Detach());
查看更多
We Are One
7楼-- · 2020-01-30 07:52
CString pngPath=L"D:\\k.png";
CImage pngImage;
CBitmap pngBmp; 
CDC bmDC;
CBitmap *pOldbmp;
BITMAP  bi;
//UINT xPos=450,yPos=300;
UINT xPos=10,yPos=10;
CClientDC dc(this);

pngImage.Load(pngPath);
// new code

pngBmp.Attach(pngImage.Detach());

bmDC.CreateCompatibleDC(&dc);

 pOldbmp= bmDC.SelectObject(&pngBmp);
 pngBmp.GetBitmap(&bi);
 dc.BitBlt(xPos,yPos,bi.bmWidth,bi.bmHeight,&bmDC,0,0,SRCCOPY);  
 bmDC.SelectObject(pOldbmp);
查看更多
登录 后发表回答