用VC实现将CView自绘图形输出为bmp文件

void CTrainView::SaveAsBmp(CString filename)
{
		//定义图形大小
	    CRect clientRC;
		this->GetClientRect(clientRC);
		int iWidth = clientRC.Width();
		int iHeight = clientRC.Height();
		int iPixel = 16;
		//图形格式参数
		BITMAPINFO *lpbmih = new BITMAPINFO;
		lpbmih->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		lpbmih->bmiHeader.biWidth = iWidth;
		lpbmih->bmiHeader.biHeight = iHeight;
		lpbmih->bmiHeader.biPlanes = 1;
		lpbmih->bmiHeader.biBitCount = iPixel;
		lpbmih->bmiHeader.biCompression = BI_RGB;
		lpbmih->bmiHeader.biSizeImage = 0;
		lpbmih->bmiHeader.biXPelsPerMeter = 0;
		lpbmih->bmiHeader.biYPelsPerMeter = 0;
		lpbmih->bmiHeader.biClrUsed = 0;
		lpbmih->bmiHeader.biClrImportant = 0;

		//创建位图数据
		HDC hdc,hdcMem;
		HBITMAP hBitMap = NULL;
		CBitmap *pBitMap = NULL;
		CDC *pMemDC = NULL;
		BYTE *pBits;

		hdc = CreateIC(TEXT("DISPLAY"),NULL,NULL,NULL);
		hdcMem = CreateCompatibleDC(hdc);
		hBitMap = CreateDIBSection(hdcMem,lpbmih,DIB_PAL_COLORS,(void **)&pBits,NULL,0);
		pBitMap = new CBitmap;
		pBitMap->Attach(hBitMap);
		pMemDC = new CDC;
		pMemDC->Attach(hdcMem);
		pMemDC->SelectObject(pBitMap);
		//
		CRect rc(0,0,iWidth,iHeight);
		pMemDC->SetBkMode(TRANSPARENT);
		//添加自绘图形
		OnDraw(pMemDC);
														//DrawCurve(pMemDC,rc);
		//保存到文件并创建位图结构
		BITMAPFILEHEADER bmfh;
		ZeroMemory(&bmfh,sizeof(BITMAPFILEHEADER));
		*((char *)&bmfh.bfType) = 'B';
		*(((char *)&bmfh.bfType) + 1) = 'M';
		bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
		bmfh.bfSize = bmfh.bfOffBits + (iWidth * iHeight) * iPixel / 8;

		TCHAR szBMPFileName[128];
		int iBMPBytes = iWidth * iHeight * iPixel / 8;
		strcpy(szBMPFileName,filename);
		CFile file;
		if(file.Open(szBMPFileName,CFile::modeWrite | CFile::modeCreate))
		{
			file.Write(&bmfh,sizeof(BITMAPFILEHEADER));
			file.Write(&(lpbmih->bmiHeader),sizeof(BITMAPINFOHEADER));
			file.Write(pBits,iBMPBytes);
			file.Close();
		}

		pMemDC->DeleteDC();
		delete pMemDC; pMemDC = NULL;
		delete pBitMap; pBitMap = NULL;
		delete lpbmih; lpbmih = NULL;
}


void CTrainView::OnFileSaveAs()
{
	// TODO: 在此添加命令处理程序代码
		CFileDialog dlg(false,NULL,NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "位图文件(*.bmp)|*.bmp|",NULL);
		if (dlg.DoModal()!= IDOK) return;
		CString filename = dlg.GetFileName() + ".bmp";
		SaveAsBmp(filename);
}
 

你可能感兴趣的:(数据结构,vc++)