ppm是一種簡單的圖像格式,僅包含格式、圖像寬高、bit數(shù)等信息和圖像數(shù)據(jù)。 圖像數(shù)據(jù)的保存格式可以用ASCII碼,也可用二進(jìn)制,下面只說說一種ppm格式中比較簡單的一種:24位彩色、二進(jìn)制保存的圖像。 文件頭+rgb數(shù)據(jù): P6\n width height\n 255\n rgbrgb... 其中P6表示ppm的這種格式;\n表示換行符;width和height表示圖像的寬高,用空格隔開;255表示每個(gè)顏色分量的最大值;rgb數(shù)據(jù)從上到下,從左到右排放。
讀取ppm圖像: // read ppm image, rgb data store in *data void read_ppm(char* filename, unsigned char** data, int* w, int* h) { char header[20]; FILE* pFile;
pFile = fopen(filename, "rb"); fgets(header, 20, pFile);// get "P6" fgets(header, 20, pFile);// get "width height" sscanf(header,"%d %d\n", w, h);
*data = (unsigned char*) malloc((*w)*(*h)*3);
// get "255" fgets(header, 20, pFile);
// get rgb data fread(*data, (*w)*(*h)*3, 1, pFile);
fclose(pFile); }
寫ppm圖像文件: // giving rgb data and image width and height, write a ppm image, void write_ppm(char* filename, unsigned char* data, int w, int h) { FILE* pFile; char header[20];
pFile = fopen(filename, "wb");
// write "P6" fwrite("P6\n", 3, 1, pFile);
// write "width height" sprintf(header, "%d %d\n", w, h); fwrite(header, strlen(header), 1, pFile);
// writeh "255" fwrite("255\n", 4, 1, pFile);
// write rgb data fwrite(data, w*h*3, 1, pFile);
fclose(pFile); }
//清理ppm數(shù)據(jù) // free ppm rgb data void free_ppmdata(unsigned char** data) { free(*data); *data = NULL; }
使用舉例: int main(int argc, char* argv[]) { unsigned char* data; int w, h;
read_ppm("C:\\test.ppm", &data, &w, &h); printf("ppm size: %dx%d\n", w, h);
write_ppm("C:\\test2.ppm", data, dw, dh);
free_ppmdata(&data);
printf("main() finished......\n"); return 0; } 可以驗(yàn)證test2.ppm跟test.ppm是完全一致的,可以用看圖軟件打開。 |