位图的像素操作练习(2012-05-25)

很久没有较长篇的代码练习了,今天偷闲回顾练习了一下位图文件的像素操作,备忘,参考了:
水平翻转,垂直翻转,转灰度:
void BMPOpt(){
BITMAPFILEHEADER fhd;
BITMAPINFOHEADER ihd;
BYTE *pDat=NULL;
CString sfnm("e:\\t.bmp");
CFile file;
if(file.Open(sfnm, CFile::modeRead)){
try{
file.Read(&fhd, sizeof(BITMAPFILEHEADER));
file.Read(&ihd, sizeof(BITMAPINFOHEADER));
int offset = fhd.bfOffBits;
int high = ihd.biHeight,
wide = ihd.biWidth,
w4B  = ((wide*3+3)/4)*4;
int bits = ihd.biBitCount;
int len = high*w4B + w4B*2; //*wide*3;
pDat = (BYTE*)malloc(len);
if(pDat){
memset(pDat, 0, len);
}else{
throw "malloc err";
}
BYTE *pLine = pDat+high*w4B;
file.Read(pDat, len);
file.Close();
//{{// flip H::
for(int i=0; i<high/2; i++){
memcpy(pLine, pDat+i*w4B, w4B);
memcpy(pDat+i*w4B, pDat+(high-1-i)*w4B, w4B);
memcpy(pDat+(high-1-i)*w4B, pLine, w4B);
}
CFile f2;
if(f2.Open("e:\\t2.bmp", CFile::modeCreate|CFile::modeWrite)){
f2.Write(&fhd, sizeof(BITMAPFILEHEADER));
f2.Write(&ihd, sizeof(BITMAPINFOHEADER));
f2.Write(pDat, high*w4B);
f2.Close();
}
//}// flip H;;
//{ flip V::
BYTE a=0, b=0, c=0;
for(int i=0; i<high; i++){
pLine = pDat+i*w4B;
for(int j=0; j<wide/2; j++){
a=pLine[j*3];
b=pLine[j*3+1];
c=pLine[j*3+2];
int pos = (wide-1-j)*3;
pLine[j*3]   = pLine[pos];
pLine[j*3+1] = pLine[pos+1];
pLine[j*3+2] = pLine[pos+2];
pLine[pos]   = a;
pLine[pos+1] = b;
pLine[pos+2] = c;
}
}
CFile f3;
if(f3.Open("e:\\t3.bmp", CFile::modeCreate|CFile::modeWrite)){
f3.Write(&fhd, sizeof(BITMAPFILEHEADER));
f3.Write(&ihd, sizeof(BITMAPINFOHEADER));
f3.Write(pDat, high*w4B);
f3.Close();
}
//}} flip V;;
//{//make gray bmp, 8bits:
int gwide = (wide+3)/4*4;
int glen = high*gwide;
BYTE *pdat2 = (BYTE*)malloc(glen+4);
memset(pdat2, 0, glen);
BYTE *p8ln = NULL;
BYTE *p24ln = NULL;
//BYTE a=0, b=0, c=0;
for(int i=0; i<high; i++){
p8ln = pdat2 + i*gwide;
p24ln = pDat + i*w4B;
for(int j=0; j<wide; j++){
a=p24ln[j*3];
b=p24ln[j*3+1];
c=p24ln[j*3+2];
p8ln[j] = (a+b+c)/3;
}
}
RGBQUAD rgb[256] = {0};
int rgblen = sizeof(rgb);
fhd.bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+gwide*high + sizeof(rgb);
ihd.biBitCount = 8;
ihd.biSize = sizeof(BITMAPINFOHEADER);
ihd.biSizeImage = 0;
ihd.biClrUsed = 256;
for(int n=0; n<0xff; n++){
rgb[n].rgbBlue = n;
rgb[n].rgbGreen = n;
rgb[n].rgbRed  = n;
}
CFile f4;
if(f4.Open("e:\\t4.bmp", CFile::modeCreate|CFile::modeWrite)){
f4.Write(&fhd, sizeof(BITMAPFILEHEADER));
f4.Write(&ihd, sizeof(BITMAPINFOHEADER));
f4.Write(&rgb, sizeof(rgb));
f4.Write(pdat2, glen);
f4.Close();
}
free(pdat2);
pdat2 = NULL;
//} //make gray bmp, 8bits;;
if(pDat!=NULL){
free(pDat);
pDat = NULL;
}
AfxMessageBox("OK");
}catch(CException *e){
CString sErr;
sErr.Format("Read Err\nerr code=%d", GetLastError());
//e->GetErrorMessage(sErr);
AfxMessageBox(sErr);
}
}else{
AfxMessageBox("Open file fail");
}

posted @ 2012-05-25 16:15  xufun  阅读(172)  评论(0编辑  收藏  举报