Windows提供了一个显示BMP、JPG、GIF的标准方法,你只需要实例化IPicture以及它的调用就可以,通过OleLoadPicture函数函数从流中读取图片并创建该图片的IPicture对象:
OleLoadPicture(pStm,dwFileSize,TRUE,IID_IPicture,(LPVOID*)&pPic);
它在MSDN里的定义如下:
STDAPI OleLoadPicture(
IStream * pStream,
//Pointer to the stream that contains picture's data
LONG lSize, //Number of bytes read from the stream
BOOL fRunmode,
//The opposite of the initial value of the picture's
// property
REFIID riid, //Reference to the identifier of the interface
// describing the type of interface pointer to return
VOID ppvObj //Address of output variable that receives interface
// pointer requested in riid
);
以下是显示我在对话框CNewFormDlg中的一个图像显示函数DisplayPic,使用它可以在一个控件上显示一幅图片,该函数可以显示BMP、JPG和GIF文件,参数如下:
char *lpImageFile 图像文件名
HWND hWnd 要显视对象句柄
int nScrWidth 显示宽度
int nScrHeight 显示高度
HRESULT CNewFormDlg::DisplayPic(char *lpImageFile, HWND hWnd, int nScrWidth, int nScrHeight)
{
HDC hDC_Temp=::GetDC(hWnd);
IPicture *pPic;
IStream *pStm;
BOOL bResult;
HANDLE hFile=NULL;
DWORD dwFileSize,dwByteRead;
//打开硬盘中的图形文件
hFile=CreateFile(lpstrFile,GENERIC_READ,
FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile!=INVALID_HANDLE_VALUE)
{
dwFileSize=GetFileSize(hFile,NULL);//获取文件字节数
if (dwFileSize==0xFFFFFFFF)
return E_FAIL;
}
else
{
return E_FAIL;
}
//分配全局存储空间
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize);
LPVOID pvData = NULL;
if (hGlobal == NULL)
{
AfxMessageBox("图形文件分配出错.");
return E_FAIL;
}
if ((pvData = GlobalLock(hGlobal)) == NULL)//锁定分配内存块
{
AfxMessageBox("内存块锁定出问题");
return E_FAIL;
}
ReadFile(hFile,pvData,dwFileSize,&dwByteRead,NULL);//把文件读入内存缓冲区
GlobalUnlock(hGlobal);
if(CreateStreamOnHGlobal(hGlobal, TRUE, &pStm) != S_OK)
{
AfxMessageBox("流初始化失败");
return E_FAIL;
}
//装入图形文件
bResult=OleLoadPicture(pStm,dwFileSize,TRUE,IID_IPicture,(LPVOID*)&pPic);
if(FAILED(bResult))
{
AfxMessageBox("图形文件装载出错.");
return E_FAIL;
}
OLE_XSIZE_HIMETRIC hmWidth;//图片的真实宽度
OLE_YSIZE_HIMETRIC hmHeight;//图片的真实高度
pPic->get_Width(&hmWidth);
pPic->get_Height(&hmHeight);
//将图形输出到屏幕上
bResult=pPic->Render(hDC_Temp,0,0,nScrWidth,nScrHeight,
0,hmHeight,hmWidth,-hmHeight,NULL);
CloseHandle(hFile);//关闭打开的文件
pPic->Release();
// Free memory.
GlobalFree(hGlobal);
if (SUCCEEDED(bResult))
{
return S_OK;
}
else
{
AfxMessageBox("图形文件装载出错.");
return E_FAIL;
}
}
调用如下:
void CNewFormDlg::OnButton2()
{
HWND m_hWnd;
GetDlgItem(IDC_STATIC_VIEW,&m_hWnd);
DisplayPic("F://图片//水晶//Crystal521.jpg",m_hWnd,500,500);
}