简述实现步骤如下:
1、通过点击浏览按钮选择JPG图像文件
点击浏览按钮打开文件对话框选择JPG图像文件,得到文件所在的路径目录。
关键代码如下:
char
szFilter[]
=
"
JPGFiles(*.jpg)|*.jpg|JPEGFiles(*.jpeg)|*.jpeg|GIFFiles(*.gif)|*.gif|AllFiles(*.*)|*.*||
"
;
CFileDialogdlg(TRUE,
"
jpg|jpeg|gif
"
,NULL,OFN_HIDEREADONLY
|
OFN_OVERWRITEPROMPT,szFilter);
if
(dlg.DoModal()
==
IDOK)
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
CStringstrPathName=dlg.GetPathName();
}
2、加载JPG文件到内存
主要通过COM类—IPicture实现。
关键代码如下:
BOOLCShowJPGDlg::LoadJPGFile(
const
char
*
pPathname)
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
CFilefile;
if(!file.Open(pPathname,CFile::modeRead))
returnFALSE;
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
DWORDm_nFileLen;
m_nFileLen=file.GetLength();
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
HGLOBALhMem=::GlobalAlloc(GMEM_MOVEABLE,m_nFileLen);
LPVOIDlpBuf=::GlobalLock(hMem);
if(file.ReadHuge(lpBuf,m_nFileLen)!=m_nFileLen)
returnFALSE;
file.Close();
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
::GlobalUnlock(hMem);
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
if(CreateStreamOnHGlobal(hMem,TRUE,&pStream)!=S_OK)
returnFALSE;
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
if(OleLoadPicture(pStream,m_nFileLen,TRUE,IID_IPicture,(LPVOID*)&pPicture)!=S_OK)
returnFALSE;
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
returnTRUE;
}
3、在屏幕上显示JPG图像
主要通过Render函数实现显示JPG图像。
Render函数说明
HRESULT Render( HDC hdc,//设备环境句柄
long x,//在hdc上的水平坐标
long y,//在hdc上的垂直坐标
long cx,//图像宽度
long cy,//图像高度
OLE_XPOS_HIMETRIC xSrc,//在源图像上的水平偏移
OLE_YPOS_HIMETRIC ySrc,//在源图像上的垂直偏移
OLE_XSIZE_HIMETRIC cxSrc,//在源图像上水平拷贝的数量
OLE_YSIZE_HIMETRIC cySrc,//在源图像上垂直拷贝的数量
LPCRECT prcWBounds//指向目标图元设备环境句柄的指针
);
关键代码如下:
void
CShowJPGDlg::DrawImage(
int
x,
int
y,CDC
*
pDC)
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
if(pPicture!=NULL)
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
...{
longnWidth,nHeight;
pPicture->get_Width(&nWidth);
pPicture->get_Height(&nHeight);
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
/**//*
//图片原大显示
CSizesz(nWidth,nHeight);
pDC->HIMETRICtoDP(&sz);
pPicture->Render(pDC->m_hDC,0,0,sz.cx,sz.cy,0,nHeight,nWidth,-nHeight,NULL);
*/
//按窗口尺寸显示
CRectrect;
GetClientRect(&rect);
pPicture->Render(pDC->m_hDC,x,y,rect.Width(),rect.Height(),0,nHeight,nWidth,-nHeight,NULL);
}
}
注意:由于是主要通过COM类—IPicture实现的,不要忘记了CoInitialize(NULL);,用完了CoUninitialize();。
显示JPEG、GIF和JPG是一样的。
相比较BMP图像,JPG、JPEG、GIF图像有很多优点。但BMP图像在VC中的处理好像更理所当然一点,相信这种COM实现显示JPG、JPEG、GIF图像的处理让我们更是耳目一新。