几天前被要求做一个位图转换的小程序。许久没有碰VC++,现在拾起来还是有点心慌慌的。果然,一打开IDE就不知道要干什么了。还好到处COPY代码的能力还有,凑出了一个还算能用的东西。唉,学什么都应该用心用力的不是??摘抄关键代码如下:
void CBMP2TXTDlg::LoadBitmap( char *strPath)
{
BITMAPFILEHEADER fileheader;
BITMAPINFOHEADER infoheader;
WORD *bitmapData;
// WORD *bitmapDone;
FILE *bitmapFile;
// char Path[100];
// strncpy(Path,(LPCTSTR)strPath,sizeof(Path));
bitmapFile = fopen(strPath, "rb"); //以二进制只读方式打开
// fseek(bitmapFile, sizeof(BITMAPFILEHEADER), SEEK_SET); //定位到BITMAPFILEHEADER以后的部分
fread(&fileheader, sizeof(BITMAPFILEHEADER), 1, bitmapFile);
fread(&infoheader, sizeof(BITMAPINFOHEADER), 1, bitmapFile);
BYTE red, green, blue;
bitmapData = new WORD[infoheader.biWidth * infoheader.biHeight]; //读入像素点数据
// bitmapDone = new WORD[infoheader.biWidth * infoheader.biHeight];
for( int y=0; y<infoheader.biHeight; y++)
{
for( int x=0; x<infoheader.biWidth; x++)
{
fread(&blue, sizeof(BYTE), 1, bitmapFile);
fread(&green, sizeof(BYTE), 1, bitmapFile);
fread(&red, sizeof(BYTE), 1, bitmapFile);
bitmapData[y*infoheader.biWidth + x] = RGB16(red, green, blue);
}
}
//设置修改后的位图信息
fileheader.bfSize=sizeof(fileheader)+sizeof(infoheader)+infoheader.biWidth * infoheader.biHeight*2+16;
fileheader.bfOffBits+=16; //多了个调色板
infoheader.biSize+=16; //调色板并入infoheader结构
infoheader.biBitCount=16;
infoheader.biCompression=BI_BITFIELDS; //RGB16(565) # define BI_BITFIELDS 3
infoheader.biSizeImage=infoheader.biWidth * infoheader.biHeight*2;
infoheader.biXPelsPerMeter=0x0EC3; //从photoshop转换后的图片中拷出
infoheader.biYPelsPerMeter=0x0EC3;
infoheader.biClrImportant=0;
//将转换完毕后的bmp写入txt
CString filepath;
filepath.Format("C://BMP.txt");
CStdioFile mFile;
CFileException mExcept;
mFile.Open(filepath,CFile::modeWrite|CFile::modeCreate,&mExcept);
CString temp;
temp.Format(_T("const char bmp[%04d]=/r/n{"),infoheader.biSizeImage);
mFile.Write(temp,temp.GetLength());
temp=Uncode(fileheader);
mFile.Write(temp,temp.GetLength());
temp=Uncode(infoheader);
mFile.Write(temp,temp.GetLength());
//写入调色板信息
temp.Format(_T("/r/n// information of Palette/r/n0X00 0XF8 0X00 0X00 0XE0 0X07 0X00 0X00 0X1F 0X00 0X00 0X00 0X00 0X00 0X00 0X00/r/n"));
mFile.Write(temp,temp.GetLength());
//写入bitmap数据
unsigned long i;
unsigned long j=infoheader.biWidth * infoheader.biHeight;
CString str;
temp.Format(_T("// data of BMPdata"));
mFile.Write(temp,temp.GetLength());
temp.Format(_T(""));
for(i=0;i<j-1;i++)
{
str.Format(_T("0X%02X,0X%02X,"),(*(bitmapData+i))&0X00FF,(*(bitmapData+i))>>8);
temp+=str;
if((i%16)==0)
{
temp+=_T("/r/n");
mFile.Write(temp,temp.GetLength());
temp.Format(_T(""));
}
}
mFile.Write(temp,temp.GetLength());
temp.Format(_T("0X%02X,0X%02X,0X00"),(*(bitmapData+j-1))>>8,(*(bitmapData+j-1))&0X00FF);
mFile.Write(temp,temp.GetLength());
temp.Format(_T("/r/n}"));
mFile.Write(temp,temp.GetLength());
mFile.Close();
delete bitmapData;
// delete bitmapDone;
AfxMessageBox("OK!!");
}