/*
HBITMAP hImage = LoadImageFromFile("c:\\kwanghee.jpg");
...
DeleteObject(hImage);
*/
HBITMAP LoadImageFromFile(LPCTSTR szFileName)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
LPVOID pvData = NULL;
HGLOBAL hGlobal = NULL;
LPPICTURE pPicture;
try
{
HRESULT hr;
DWORD dwFileSize;
// 파일 열기
hFile = CreateFile(szFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
// 파일이 없을 경우
if(hFile == INVALID_HANDLE_VALUE)
{
TRACE("GetBitmapFromFile() File Open Error");
throw -1;
}
// 파일 크기 얻기
dwFileSize = GetFileSize(hFile, NULL);
if(dwFileSize == -1)
{
TRACE("GetBitmapFromFile() File Read Error");
throw -1;
}
// 파일 크기만큼 동적할당
hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize);
if(hGlobal == NULL)
{
TRACE("GetBitmapFromFile() GlobalAlloc Error");
throw -1;
}
pvData = GlobalLock(hGlobal);
if(pvData == NULL)
{
TRACE("GetBitmapFromFile() GlobalLock Error");
throw -1;
}
DWORD dwBytesRead = 0;
BOOL bRead = ReadFile(hFile, pvData, dwFileSize, &dwBytesRead, NULL);
if(!bRead)
{
TRACE("GetBitmapFromFile() ReadFile Error");
throw -1;
}
GlobalUnlock(hGlobal);
CloseHandle(hFile);
LPSTREAM pstm = NULL;
hr = CreateStreamOnHGlobal(hGlobal, TRUE, &pstm);
if(S_OK != hr || pstm == NULL)
throw -1;
// Stream 에서 IPicture 를 생성
hr = ::OleLoadPicture(pstm, dwFileSize, FALSE, IID_IPicture, (LPVOID *)&pPicture);
if(S_OK != hr || pPicture == NULL)
{
TRACE("Graphic File Load Error");
return false;
}
pstm->Release();
GlobalFree(hGlobal);
HBITMAP PicHandle;
pPicture->get_Handle((unsigned int *)&PicHandle);
HBITMAP NewHandle = (HBITMAP)CopyImage(PicHandle, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG);
pPicture->Release();
return NewHandle;
}
catch (int e)
{
UNREFERENCED_PARAMETER (e);
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
if (hGlobal)
{
GlobalUnlock(hGlobal);
GlobalFree(hGlobal);
}
if (pPicture)
pPicture->Release();
return NULL;
}
}