Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

visual-c++

mfc

Hi i want to load png images and jpeg images.

can anyone help me?

like image 696
Ashish Avatar asked Mar 22 '10 07:03

Ashish


4 Answers

CImage image;
image.Load(_T("C:\\image.png")); // just change extension to load jpg
CBitmap bitmap;
bitmap.Attach(image.Detach());
like image 185
Nikola Smiljanić Avatar answered Oct 22 '22 14:10

Nikola Smiljanić


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

like image 35
Alex F Avatar answered Oct 22 '22 14:10

Alex F


//----- 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;
}
like image 21
Paolo Biagini Avatar answered Oct 22 '22 12:10

Paolo Biagini


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.

like image 40
sorrymissjackson Avatar answered Oct 22 '22 13:10

sorrymissjackson