1.生成BMP圖片
在學習圖形圖像的過程中,最簡單和常見的格式是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 }
上述代碼生成一幅寬和高均為200的BMP隨機位圖。如圖所示:
BMP格式說明,待續。。。
2.生成PNG圖片
miloyip給出了生成無壓縮PNG圖片所需的最少的ANSI C 代碼,詳情見:https://github.com/miloyip/svpng。
補充:LodePNG是一個集合了PNG圖像解碼器和編碼器的代碼文件,不依賴於諸如zlib和libpng的外部鏈接/庫,提供方便友好的PNG編解碼器調用方法。LodePNG主要是采用C(ISO C90)編寫的,並提供了C++的接口。LodePNG的使用非常簡單,只要在項目文件中包含lodepng.cpp和lodepng.h或者lodepng.c和lodepng.h就可以。
3.生成JPEG圖片
SuperSodaSea給出了生成JPEG圖片的C++代碼,詳情見:https://github.com/SuperSodaSea/svjpeg。