CBitmap bkBMP; // BMP位图后台buffer
// 打开位图文件
void CGraphic::OnBnClickedBtnLoadbmp()
{
// TODO: Add your control notification handler code here
//--------------------------------------------------------------------
// 打开BMP位图并显示出来
//--------------------------------------------------------------------
CFileDialog openDlg(true,"*.bmp",NULL,NULL,"*.bmp|*.bmp||"); // creat open BMP dialog
if (openDlg.DoModal()==IDOK) // finish the photo choose
{
CString bmpName = openDlg.GetPathName(); // get BMP photo path
// 通过LoadImage获取位图数据,转存人BMP后台buffer
bkBMP.m_hObject = (HBITMAP)::LoadImage(NULL,bmpName,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
}
else
return;
//--------------------------------------------------------------------
// 将打开的BMP位图数据取出
//--------------------------------------------------------------------
CBitmap* m_bBmp; // all BMP photo information buffer
m_bBmp = NULL;
if (m_bBmp != NULL)
{
m_bBmp->DeleteObject();
delete m_bBmp;
m_bBmp = NULL;
}
m_bBmp = new CBitmap; // set RAM for m_pBmp
LoadBitmapFile(openDlg.GetPathName(),*m_bBmp); // load all BMP photo information to buffer
BITMAP infBmp; // 创建一个BMP结构体,存储BMP位图信息
m_bBmp -> GetBitmap(&infBmp); // 这个结构体buffer接收打开的位图信息
delete m_bBmp;
// 将信息一一取出
int bmType = infBmp.bmType;
bmpCol = infBmp.bmWidth;
bmpRow = infBmp.bmHeight;
int widthBytes = infBmp.bmWidthBytes;
int planes = infBmp.bmPlanes;
int bitspixel = infBmp.bmBitsPixel;
m_graDlg_staBMPInfm.Format("bmType=%d, bmWidth=%d, bmHeight=%d, bmWidthBytes=%d, bmPlanes=%d, bmBitsPixel=%d",
bmType,bmpCol,bmpRow,widthBytes,planes,bitspixel);
SetDlgItemText(IDC_STA_BMPINF,m_graDlg_staBMPInfm); // 显示信息
Invalidate(); // 相应OnPaint消息
}
// 显示位图
void CGraphic::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
CDC * pDC;
pDC = GetDlgItem(IDC_BMP_DISPLAY)->GetDC(); // 获取picture控件DC
CDC * bkDc = new CDC; // 创建后台DC buffer
bkDc -> CreateCompatibleDC(pDC); // 后台DC与picture控件DC相关联
bkDc -> SelectObject(bkBMP); // 后台DC存入之前已导入的BMP位图
// pDC -> BitBlt(0,0,bmpCol,bmpRow,bkDc,0,0,SRCCOPY); // picture控件显示(这种显示方法图片不能缩放)
pDC -> SetStretchBltMode(HALFTONE); // 调整图片缩放颜色失真
pDC -> StretchBlt(0,0,BMP_STRETCH_WIDTH,BMP_STRETCH_HEIGHT,bkDc,0,0,bmpCol,bmpRow,SRCCOPY); // 将图片按比例缩放
delete bkDc; // 不加此句,更改窗口大小时会影响BMP位图显示
}
关于StretchBlt函数和BitBlt函数的用法 参考:http://blog.csdn.net/phenixyf/article/details/41827349
关于StretchBlt函数缩放后失真 参考:http://blog.csdn.net/phenixyf/article/details/41827715