位图由位图文件头、位图信息头、颜色表、位图像素数据四部分组成,网上关于位图文件结构介绍的资料很多,这里就不再赘述。
下面我们主要介绍一下位图文件的读取。
一. 读取位图文件
1. 头文件中添加如下变量
CString strFileName; //打开文件名
BITMAPFILEHEADER bmfHeader; //位图文件头
BITMAPINFOHEADER bmiHeader; //位图信息头
void* pimage; //位图数据
RGBQUAD* pRgbQuad; //颜色表
long number_image //位图数据大小
2. 添加打开消息响应函数OnFileOpen()
//弹出打开对话框
CFileDialog dlg(TRUE,TEXT("BMP"),0,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,TEXT("位图文件(*.BMP)|*.BMP||"),this);
dlg.m_ofn.lpstrTitle = "Open Bitmap";
if(dlg.DoModal() != IDOK)
return;
//打开位图文件
CFile file;
strFileName=dlg.GetPathName();
if(file.Open(strFileName, CFile::modeRead | CFile::shareDenyNone, NULL) == 0)
{
AfxMessageBox("File open failed.");
return;
}
//读取位图文件头
file.Read(&bmfHeader, sizeof(bmfHeader));
if(bmfHeader.bfType != (*(WORD*)"BM")) //0x4d42
{
AfxMessageBox("File type error.");
return;
}
if(file.GetLength() != bmfHeader.bfSize)
{
AfxMessageBox("File is demaged.");
return;
}
//读取位图信息头
file.Read(&bmiHeader, sizeof(bmiHeader));
//读取颜色表
if(bmiHeader.biBitCount == 8) //256色位图
{
pRgbQuad = new RGBQUAD[256];
file.Read(pRgbQuad, sizeof(RGBQUAD)*256);
}
else if(bmiHeader.biBitCount != 24)
{
AfxMessageBox("Only 24bit and 8bit could be opened.");
return;
}
//读取位图数据
int lineByte = (bmiHeader.biWidth*bmiHeader.biBitCount/8+3)/4*4;
number_image = lineByte*(bmiHeader.biHeight);
pimage = new BYTE[number_image];
file.Read(pimage, number_image);
file.Close();