BMP header 有54 byte
memory 擺放的順序為 由下至上, 由左至右
pixel 順序為 B ,G, R 而不是 RGB
每個 pixel 所佔的size 可以設定成 4 byte or 3 byte
BMP 有個限制, 每個 row 所佔的 memory byte數必須是 4 的倍數
為了簡化 這個 alignment 的問題 所以下面的範例選用 每個pixel佔據 4個byte
目前只完成 把mono image 轉成RGB,
//verifed
void WriteMonoImg2BMP(char* filename,double* buffer ,int img_width, int img_height,double div)
{
unsigned int width=img_width, height=img_height;
unsigned int datlen=img_width*img_height;
unsigned int file_size ;
unsigned int rgb_raw_data_offset=54;
unsigned char *pBmpBuffer;
int pixel_bytes=4;
int databytes;
int i;
string str1,str2;
int found;
str1=filename;
found=str1.find_last_of("/\\");
str2=str1.substr(0,found+1);
CreateDir((char*)str2.c_str());
databytes=width*height*pixel_bytes;
pBmpBuffer= new unsigned char[databytes];
unsigned char header[54] = {
0x42, // identity : B
0x4d, // identity : M
0, 0, 0, 0, // file size
0, 0, // reserved1
0, 0, // reserved2
54, 0, 0, 0, // RGB data offset
40, 0, 0, 0, // struct BITMAPINFOHEADER size
0, 0, 0, 0, // bmp width
0, 0, 0, 0, // bmp height
1, 0, // planes
32, 0, // bit per pixel
0, 0, 0, 0, // compression
0, 0, 0, 0, // data size
0, 0, 0, 0, // h resolution
0, 0, 0, 0, // v resolution
0, 0, 0, 0, // used colors
0, 0, 0, 0 // important colors
};
// file size
file_size = width * height * 4 + rgb_raw_data_offset;
header[2] = (unsigned char)(file_size & 0x000000ff);
header[3] = (file_size >> 8) & 0x000000ff;
header[4] = (file_size >> 16) & 0x000000ff;
header[5] = (file_size >> 24) & 0x000000ff;
// width
header[18] = width & 0x000000ff;
header[19] = (width >> 8) & 0x000000ff;
header[20] = (width >> 16) & 0x000000ff;
header[21] = (width >> 24) & 0x000000ff;
// height
header[22] = height &0x000000ff;
header[23] = (height >> 8) & 0x000000ff;
header[24] = (height >> 16) & 0x000000ff;
header[25] = (height >> 24) & 0x000000ff;
// because bmp layout is from bottom to top ,
// need upside down image
int j, x,y,t,s;
double a;
unsigned char temp;
for(i=0;i<height;i++)
{
for(j=0;j<width;j++)
{
t=((i*width)+j)*pixel_bytes;
y=height-i-1;
x=j;
s= (y*width+x);
a= (buffer[s]/div);
a= a>255.0? 255.0 : a;
a= a<0.0 ? 0: a;
temp=(unsigned char)floor(a);
pBmpBuffer[t+0]=temp; //B
pBmpBuffer[t+1]=temp; //G
pBmpBuffer[t+2]=temp; //R
pBmpBuffer[t+3]=0;
}
}
ofstream fout;
fout.open(filename,ios_base::out|ios_base::binary|ios_base::trunc);
fout.write ((char*)header, 54);
fout.write ((char*)pBmpBuffer, databytes);
fout.close();
/
*/
}
沒有留言:
張貼留言