BMP位图格式分析
如下是我打开BMP文件的相应函数,结果图片能显示在视图中,但是却不对,图片是斜的,是倒置的,不理解,求指点
void CBMPView::OnFileOpen()
{
// TODO: 在此添加命令处理程序代码
CFileDialog fileDlg(TRUE);
//注意过滤器组的写法
//1.每一组过滤器由一对字符串构成(每个字符串以\0结尾),第一个字符串是类型说明,
//第二个字符串则是过滤格式,如果一组过滤器对多种格式过滤,不同的格式间用分号隔开
//每一种格式由*.加上拓展名构成。
//2.如果有多组过滤,那么有几组过滤就有几组字符串。
//3.实例
//fileDlg.m_ofn.lpstrFilter =L"位图文件(*.bmp),文本文件(*.txt)\0*.bmp;*.txt\0音频文件(.mp3)\0*.mp3\0";
fileDlg.m_ofn.lpstrFilter =L"位图文件\0*.bmp\0";
if(IDOK == fileDlg.DoModal())
{
//打开BMP文件
CFile openFile(fileDlg.m_ofn.lpstrFile, CFile::modeRead | CFile::typeBinary);
//获取位图文件头、信息头
BITMAPFILEHEADER bmpFileHeader;
openFile.Read(&bmpFileHeader, 14);
BITMAPINFOHEADER bmpInfHeader;
openFile.Read(&bmpInfHeader, 40);
//绘制视图
CDC* pDC = GetDC();
openFile.Seek(bmpFileHeader.bfOffBits, CFile::begin);
if(bmpInfHeader.biBitCount == 24)
{
RGBTRIPLE* pRGB3;
pRGB3 = new RGBTRIPLE[bmpInfHeader.biWidth * bmpInfHeader.biHeight];
openFile.Read(pRGB3, bmpInfHeader.biWidth * bmpInfHeader.biHeight * 3);
for(int i=0; i< bmpInfHeader.biHeight; i++)
{
for(int j =0; j< bmpInfHeader.biWidth; j++)
{
pDC->SetPixelV(j, bmpInfHeader.biHeight - i, RGB(pRGB3[i*bmpInfHeader.biWidth+j].rgbtRed,pRGB3[i*bmpInfHeader.biWidth+j].rgbtGreen,pRGB3[i*bmpInfHeader.biWidth+j].rgbtBlue));
}//这里纵坐标如果直接用i图像显示出来是倒置的
}
delete [] pRGB3;
}
else if(bmpInfHeader.biBitCount == 32)
{
RGBQUAD* pRGB4;
pRGB4 = new RGBQUAD[bmpInfHeader.biWidth * bmpInfHeader.biHeight];
openFile.Read(pRGB4, bmpInfHeader.biWidth * bmpInfHeader.biHeight * 4);
for(int i=0; i< bmpInfHeader.biHeight; i++)
{
for(int j =0; j< bmpInfHeader.biWidth; j++)
{
pDC->SetPixelV(j, bmpInfHeader.biHeight - i, RGB(pRGB4[i*bmpInfHeader.biWidth+j].rgbRed,pRGB4[i*bmpInfHeader.biWidth+j].rgbGreen,pRGB4[i*bmpInfHeader.biWidth+j].rgbBlue));
}
}
delete [] pRGB4;
}
else
{
MessageBox(L"不支持的位图格式");
}
openFile.Close();
ReleaseDC(pDC);
}
}
[解决办法]
32位图正好是4字节对齐
BMP的y坐标系是不是从上往下,是从下往上.