2009年8月12日星期三

一个在LINUX下生成BMP的程序

很多人都搞不定内存对齐的问题,最近帮老焦他们写测试程序,用到一个BMP
GENERATOR,写了个比较简单的版本,仅针对24位真彩,现把代码公布

#include <iostream>
using namespace std;
typedef long BOOL;
typedef long LONG;
typedef unsigned char BYTE;
typedef unsigned long DWORD;
typedef unsigned short WORD;
typedef struct {
WORD bfType;//2
DWORD bfSize;//4
WORD bfReserved1;//2
WORD bfReserved2;//2
DWORD bfOffBits;//4
}__attribute__((packed))FileHead;
typedef struct{
DWORD biSize;//4
LONG biWidth;//4
LONG biHeight;//4
WORD biPlanes;//2
WORD biBitCount;//2
DWORD biCompress;//4
DWORD biSizeImage;//4
LONG biXPelsPerMeter;//4
LONG biYPelsPerMeter;//4
DWORD biClrUsed;//4
DWORD biClrImportant;//4
}__attribute__((packed))Infohead;
/*typedef struct
{
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
unsigned char rgbReserved;
}RGBQuad;//it may be useless*/
typedef struct
{
BYTE b;
BYTE g;
BYTE r;
}RGB_data;//RGB TYPE
int bmp_generator(char * filename,int width,int height,unsigned char *data)
{
FileHead bmp_head;
Infohead bmp_info;
int size = width*height*3;
//Test data
/* RGB_Test bmp_data[width][height];
int i,j;
for (i=0;i<width;i++)
for (j=0;j<height;j++)
{
bmp_data[i][j].g=bmp_data[i][j].b=0;
bmp_data[i][j].r=0xff;
}
*/
bmp_head.bfType=0x4d42;
bmp_head.bfSize=size+sizeof(FileHead)+sizeof(Infohead);//24+head+info
no quad
bmp_head.bfReserved1=bmp_head.bfReserved2=0;
bmp_head.bfOffBits=bmp_head.bfSize-size;
//finish the initial of head
bmp_info.biSize=40;
bmp_info.biWidth=width;
bmp_info.biHeight=height;
bmp_info.biPlanes=1;
bmp_info.biBitCount = 24;
bmp_info.biCompress=0;
bmp_info.biSizeImage=size;
bmp_info.biXPelsPerMeter=0;
bmp_info.biYPelsPerMeter=0;
bmp_info.biClrUsed=0;
bmp_info.biClrImportant=0;
//finish the initial of infohead;
//copy the data

// fstream file3(filename);
FILE *fp;
if(!(fp=fopen(filename,"wb"))) return 0;
//zhunan 2.6.00:58
fwrite(&bmp_head,1,sizeof(FileHead),fp);
fwrite(&bmp_info,1,sizeof(Infohead),fp);
fwrite(data,1,size,fp);
fclose(fp);

return 1;


}

int main(int argc,char **argv)
{
int i,j;
RGB_data buffer[512][512];
// cout<<"usage:bmp_generator width height"<<endl;
cout<<"programmed by zhunan"<<endl;
cout<<"API Guide:"<<endl;
cout<<"bmp_generator(char * filename,int width,int height,unsigned
char * data);"<<endl;
memset(buffer, 0, sizeof(buffer));
//please edit width and height here
//zhunan testdata
//hard coding
for (i=0;i<256;i++)
for (j=0;j<256;j++)
{
// buffer[i][j].g=buffer[i][j].b=0x00;
buffer[i][j].r=0xff;
}
bmp_generator("/home/zhunan/1234.bmp",512,512,(BYTE*)buffer);
return 1;
}

没有评论: