bool RotateBmp(const char* szFileName)
{
// 读取文件头
BITMAPFILEHEADER strBmpHead;
BITMAPINFOHEADER strBmpBitmap;
RGBQUAD bmprgb1 = {0,0,0,0};
RGBQUAD bmprgb2 = {255,255,255,0};
byte *pAllContent=NULL;
memset((void*)&strBmpHead, 0, sizeof(strBmpHead));
memset((void*)&strBmpBitmap,0, sizeof(strBmpBitmap));
CFile openFile;
char filehead[sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)];
//char conent_information[40];
if(!openFile.Open(szFileName, CFile::modeRead))
{
return false;
}
if(openFile.Read(filehead, sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)) != sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER))
{
//this->MessageBox("读取数据失败!");
openFile.Close();
return false;
}
memcpy((void*)&strBmpHead, filehead, sizeof(BITMAPFILEHEADER));
memcpy((void*)&strBmpBitmap, filehead+sizeof(BITMAPFILEHEADER),sizeof(BITMAPINFOHEADER));
if(0x424d == strBmpHead.bfType)
{
//this->MessageBox("文件格式错误!");
openFile.Close();
return false;
}
if (1 != strBmpBitmap.biBitCount)
{
openFile.Close();
return false;
}
if (openFile.Read((void*)&bmprgb1, sizeof(bmprgb1)) != sizeof(bmprgb1))
{
openFile.Close();
return false;
}
if (openFile.Read((void*)&bmprgb2, sizeof(bmprgb2)) != sizeof(bmprgb2))
{
openFile.Close();
return false;
}
DWORD allLength = strBmpHead.bfSize - strBmpHead.bfOffBits;
openFile.Seek(strBmpHead.bfOffBits, CFile::begin);
//将数据进行分析,数据时正确读出来。
pAllContent = new byte[sizeof(byte)*allLength];
if(NULL == pAllContent)
{
// MessageBox("开辟空间失败!");
openFile.Close();
return false;
}
DWORD length = openFile.Read(pAllContent, allLength);
if(allLength != length)
{
//this->MessageBox("文件长度错误,读取数据失败!");
openFile.Close();
return false;
}
openFile.Close();
//分配空间
LONG nNewWidth = strBmpBitmap.biHeight;
LONG nNewHeight = strBmpBitmap.biWidth ;
LONG nNewBMPRowByte = ((nNewWidth*strBmpBitmap.biBitCount + 31)/8)/4*4; //一行占得字节数
//将数据进行分析,数据时正确读出来。
byte *pNewAllContent = new byte[nNewHeight * nNewBMPRowByte + 1];
if(NULL == pNewAllContent)
{
return false;
}
memset(pNewAllContent, 0, nNewHeight * nNewBMPRowByte + 1);
LONG nBmpRowByte = ((strBmpBitmap.biWidth*strBmpBitmap.biBitCount + 31)/8)/4*4;
// 转存数据
for (int row = 0 ; row < strBmpBitmap.biHeight; row ++ )
{
for(int col = 0; col < strBmpBitmap.biWidth; col ++)
{
if (pAllContent[row * nBmpRowByte + col / 8] & (0x01 << (7 - col % 8)))
{
pNewAllContent[(nNewHeight - col - 1) * nNewBMPRowByte + row / 8] |= 0x01 << (7 - row % 8);
}
}
}
if(!openFile.Open(szFileName, CFile::modeCreate | CFile::modeWrite))
{
return false;
}
strBmpBitmap.biWidth = nNewWidth;
strBmpBitmap.biHeight = nNewHeight;
openFile.Write((void*)&strBmpHead, sizeof(strBmpHead));
openFile.Write((void*)&strBmpBitmap, sizeof(strBmpBitmap));
openFile.Write((void*)&bmprgb1, sizeof(bmprgb1));
openFile.Write((void*)&bmprgb2, sizeof(bmprgb2));
openFile.Write(pNewAllContent, nNewHeight * nNewBMPRowByte);
openFile.Close();
delete []pAllContent;
pAllContent = NULL;
delete []pNewAllContent;
pNewAllContent = NULL;
return true;
}
注意
1、前原图的行、列 与新图的行列反转,位运算是也要对应。