tqsheng

go.....
随笔 - 366, 文章 - 18, 评论 - 101, 引用 - 0
数据加载中……

ppm图像格式 bmp

ppm图像格式
2010-07-29 22:19
ppm是一种简单的图像格式,仅包含格式、图像宽高、bit数等信息和图像数据。 
图像数据的保存格式可以用ASCII码,也可用二进制,下面只说说一种ppm格式中比较简单的一种:24位彩色、二进制保存的图像。
文件头+rgb数据:
P6\n
width height\n
255\n
rgbrgb...
其中P6表示ppm的这种格式;\n表示换行符;width和height表示图像的宽高,用空格隔开;255表示每个颜色分量的最大值;rgb数据从上到下,从左到右排放。

读取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数据
// 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;
}
可以验证test2.ppm跟test.ppm是完全一致的,可以用看图软件打开。

posted on 2013-11-28 17:27 tqsheng 阅读(707) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理