您的位置:首页 > 编程语言

生成bmp图形文件的代码

2014-11-27 18:06 609 查看
bmp文件的生成代码需要注意三个问题:

1. 定义bmp文件头,必须要加 __attribute__((packed)),意思是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。否则编译器自动对齐之后,BMP_FILE_HEADER本来应该是14字节,就变成了16字节,这样生成的bmp文件整个就乱了,就不能被当作一个图形文件来查看了。

2. bmp文件内的像素数据,其宽度必须是4字节的倍数,也就是说下面代码中bmpinfo.biWidth必须是4的倍数。

3. bmpinfo.biBitCount = 24; 我这里用的是rgb格式的数据,所以每个像素点是24bit。

代码如下:

#include

#include

#include

// bmp headers

typedef struct __attribute__((packed))

{

    unsigned
short bfType;

    unsigned
int   bfSize;

    unsigned
short bfReserved1;

    unsigned
short bfReserved2;

    unsigned
int   bfOffBits;

} BMP_FILE_HEADER;

typedef struct __attribute__((packed))

{

    unsigned
int   biSize;

   
int           
biWidth;

   
int           
biHeight;

    unsigned
short biPlanes;

    unsigned
short biBitCount;

    unsigned
int   biCompression;

    unsigned
int   biSizeImage;

   
int           
biXPelsPerMeter;

   
int           
biYPelsPerMeter;

    unsigned
int   biClrUsed;

    unsigned
int   biClrImportant;

} BMP_INFO_HEADER;

int main()

{

    unsigned int
width = 40;

    unsigned int
height = 40;

    

  
 BMP_INFO_HEADER bmpinfo;

  
 bmpinfo.biSize = sizeof(BMP_INFO_HEADER);

  
 bmpinfo.biWidth = width;

  
 bmpinfo.biHeight = height;

  
 bmpinfo.biPlanes = 1;

  
 bmpinfo.biBitCount = 24; //RGB

  
 bmpinfo.biCompression = 0;

  
 bmpinfo.biSizeImage = width * height * 3;

  
 bmpinfo.biXPelsPerMeter = 1;

  
 bmpinfo.biYPelsPerMeter = 1;

  
 bmpinfo.biClrUsed = 0;

  
 bmpinfo.biClrImportant = 0;

  
 BMP_FILE_HEADER bmpfile;

  
 bmpfile.bfType = 0x4D42;

  
 bmpfile.bfSize = sizeof(BMP_FILE_HEADER) +
sizeof(BMP_INFO_HEADER) + (3 * (width * height));

  
 bmpfile.bfReserved1 = 0;

  
 bmpfile.bfReserved2 = 0;

  
 bmpfile.bfOffBits = sizeof(BMP_FILE_HEADER) +
sizeof(BMP_INFO_HEADER);

    

    FILE *
outfile = NULL;

    const char*
filename="test.bmp";

    unsigned
char* a = NULL;

    a =
(unsigned char*)malloc(width* height * 3);

    if(a ==
NULL) {

       
fprintf(stderr, "failed to malloc.\n");

       
return -1;

    }

    memset(a,
221, width* height * 3);

    

    int i =
0;

    for(i=0; i
< 40; i++) {

       
a[i*width*3 + i*3]=0;

       
a[i*width*3 + i*3+1]=0;

       
a[i*width*3 + i*3+2]=0;

    }

    if ((outfile
= fopen(filename, "w+b")) == NULL) {

       
fprintf(stderr, "\r\n Open %s failed!", filename);

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: