文档类代码:(在文档中操作数据)
void CCImageDoc::OnOpenImage()
{
CString strFilter;
CSimpleArray<GUID> aguidFileTypes;
HRESULT hResult;
hResult = pImg[0]->GetExporterFilterString(strFilter,aguidFileTypes);
if (FAILED(hResult))
return;
CFileDialog dlg(TRUE, NULL, NULL, OFN_FILEMUSTEXIST, strFilter);
dlg.m_ofn.nFilterIndex = m_nFilterLoad;
hResult = (int)dlg.DoModal();
if(hResult != IDOK)
return;
m_nFilterLoad = dlg.m_ofn.nFilterIndex;
m_FileName = dlg.GetFileName();
if (!SaveCanvas.IsNull())
SaveCanvas.Destroy();
hResult = SaveCanvas.Load(m_FileName);
if (FAILED(hResult))
return;
if (ImageType(pImg[0])<2)
LowTypeToIndex(pImg[1],pImg[0]);
else
ImageCopy(pImg[1],pImg[0]);
SetPathName(m_FileName,1);
UpdateAllViews(NULL);
m_nFArea=0;
}
void CCImageDoc::OnSaveImage()
{
CString strFilter;
CSimpleArray<GUID> aguidFileTypes;
CString strFileName;
CString strExtension;
HRESULT hResult;
hResult=SaveCanvas.GetExporterFilterString(strFilter,aguidFileTypes);
if(FAILED(hResult)) return;
CFileDialog dlg(FALSE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_EXPLORER,strFilter);
dlg.m_ofn.nFilterIndex=m_nFilterLoad;
hResult=(int)dlg.DoModal();
if(hResult!=IDOK)
return;
strFileName=dlg.m_ofn.lpstrFile;//取对话框中输入的文件名
if(dlg.m_ofn.nFileExtension==0)
{
switch(dlg.m_ofn.nFilterIndex)
{ case 1:
strExtension="bmp";
break;
case 2:
strExtension="jpg";
break;
case 3:
strExtension="gif";
break;
case 4:
strExtension="tif";
break;
case 5:
strExtension="png";
break;
default:
break;
}
strFileName=strFileName+'.'+strExtension;//文件名补上后缀
}
hResult=WorkCanvas.Save(strFileName);//图像存盘
if(FAILED(hResult)) return;
SetPathName(strFileName,1);
}
在视图中显示图片的代码:
定义一个函数(把内存图片显示到窗口)
void CCImageView::WorkCanvusToWindow() //将内存画布送入窗口
{
CClientDC dc(this);
struct IMAGEPARAMENT p;
if (SaveCanvas.IsNull()) return;
GetImageParament(&WorkCanvas,&p);//读取位图的参数
WorkCanvas.BitBlt(dc,0,0,p.nWidth,p.nHeight,0,0,SRCCOPY);//位块传输实现显示
}
函数分析:
用到了结构
struct IMAGEPARAMENT {
int nWidth;
int nHeight;
int nBitCount;
int nBytesPerLine;
int nBytesPerPixel;
int nNumColors;
int nSize;
};
void GetImageParament(CImage *pImg,struct IMAGEPARAMENT *ppImgParam);
//读取位图参数
void GetImageParament(CImage *pImg,struct IMAGEPARAMENT *ppImgParam)
{
if (pImg->IsNull()) return;
ppImgParam->nWidth = pImg->GetWidth();
ppImgParam->nHeight = pImg->GetHeight();
ppImgParam->nBitCount = pImg->GetBPP();
ppImgParam->nBytesPerLine = (pImg->GetWidth()*pImg->GetBPP()+31)/32*4;
ppImgParam->nBytesPerPixel = pImg->GetBPP()/8;
if (pImg->GetBPP()<=8)
ppImgParam->nNumColors= 1 << pImg->GetBPP();
else
ppImgParam->nNumColors= 0;
ppImgParam->nSize = ppImgParam->nBytesPerLine*ppImgParam->nHeight;
}
详细代码请参考-陆宗骐-Visual C++.NET图像处理编程(笔记1)-图片的创建和显示(Demo1)