How to load a JPG from resource ID?

  • Thread starter Thread starter Yan Yang
  • Start date Start date
Y

Yan Yang

Guest
I tried to load a JPG image from resource ID. I referred to the code in the link below, which is for "PNG", I replace it with "JPG".

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

However I got a strange result - the displayed image seems overlaid, which has darker colour, thicker edges and some shading. Could you please let me know the problem in the code?

Thanks in advance.

CImage image;

LPCTSTR lpszResourceName = MAKEINTRESOURCE(nIDImage);
HINSTANCE hInst1 = AfxFindResourceHandle(lpszResourceName, _T("JPG"));

HRSRC hResource = FindResource(hInst1, lpszResourceName, _T("JPG"));
if (hResource == NULL)
return;

HGLOBAL hGlobal = LoadResource(hInst1, hResource);
if (hGlobal == NULL)
return;

LPVOID lpBuffer = LockResource(hGlobal);
if (lpBuffer == NULL)
{
FreeResource(hGlobal);
return;
}

DWORD dwImageSize = SizeofResource(hInst, hResource);
HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, dwImageSize);

if (hBuffer != NULL)
{
LPVOID lpResBuffer = GlobalLock(hBuffer);
if (lpResBuffer != NULL)
{
memcpy(lpResBuffer, lpBuffer, dwImageSize);

IStream *pStream = NULL;
HRESULT hResult = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);

if (hResult == S_OK)
{
image.Load(pStream);
pStream->Release();
}
GlobalUnlock(hBuffer);
}
GlobalFree(hBuffer);
}

UnlockResource(hGlobal);
FreeResource(hGlobal);

HBITMAP hBitmap = image.Detach();
GetParent()->GetPropertySheet()->SetControlImage(hBitmap);

Continue reading...
 
Back
Top