在学习图形图像的过程中,最简单和常见的格式是BMP和PPM。下面将给出生成BMP的极度精简代码,然后讲解BMP格式。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define w 200 4 #define h 200 5 void WriteBMP(char*img,const char* filename) 6 { 7 int l=(w*3+3)/4*4; 8 int bmi[]= {l*h+54,0,54,40,w,h,1|3*8<<16,0,l*h,0,0,100,0}; 9 FILE *fp = fopen(filename,"wb"); 10 fprintf(fp,"BM"); 11 fwrite(&bmi,52,1,fp); 12 fwrite(img,1,l*h,fp); 13 fclose(fp); 14 } 15 int main() 16 { 17 char img[w*h*3]; 18 for(int i=0; i<w*h*3; i++)img[i]=rand()%256; 19 WriteBMP(img,"test.bmp"); 20 system("test.bmp"); 21 return 0; 22 }