孙其功陪你学之——C语言读取.ppm文件

来源:互联网 发布:淘宝专柜代购 编辑:程序博客网 时间:2024/05/20 07:37

C语言读取.ppm图像文件,读取的是每一个像素点的R、G、B的之0——255之间

在写读取程序时遇到好多问题,比如类型转换问题最是头疼,数据量特别大,开始读出的数据

可能有好大一部分为0,导致误认为读取错误,本人将读出的数据放在一个一维数组中,你也

可以把他们放在自己定义的三维数组中,分别存放一个像素点的RGB值,这样会更加形象,容易使用。

但功夫不负有心人,终于搞定,

在此分享


希望能给大家有所帮助,如果分析中有不恰当的地方,望批评指正

 

unsigned char matppm[640*480*3];

int nextline(char *line, FILE *fp)
{
 char *p;
 do {
  p = fgets(line, HEADER_MAXLINE, fp);
 } while ( p != NULL && *p == '#' );
 if( p==NULL )
  return -1;
 return 0;
}

int read_header(FILE *fin, int *widthp, int *heightp, int *maxvalp, int *comp)
{
 char line[HEADER_MAXLINE];
 int  cols,rows,maxval;
 if(nextline(line, fin)!=0) return -10;
 if(strncmp(line,"P5",2)==0) 
  *comp=1;
 else if (strncmp(line,"P6",2)==0)
  *comp=3;
 else if (strncmp(line,"P7",2)==0)
  *comp=4;
 else
  return -1;
 if(strlen(line)>3)
 {
  if(sscanf(line+2,"%d %d %d",&cols,&rows,&maxval )!=3 )
   return -1;
 }
 else
 {
  if(nextline(line, fin)!=0) return -10;
  if(sscanf(line,"%d %d",&cols,&rows)!=2 )
   return -1;
  if(nextline(line, fin)!=0) return -10;
  if(sscanf(line,"%d",&maxval)!=1)
   return -1;
 }
 *widthp = cols;
 *heightp = rows;
 *maxvalp = maxval;
 return 0;
}

void read_ppm_image(char * image_name , int * rows, int * cols)
{
 FILE * fp;
 int widthp;
 int heightp;
 int maxvalp;
 int comp;
  short max=0;
 fp = fopen(image_name, "rb");
 read_header(fp, &widthp, &heightp, &maxvalp,&comp);
  *rows = heightp;
  *cols = widthp;
  fread(matppm,1,widthp * heightp*3,fp);
  fclose(fp);
}

在main()函数中应用如下:

int rows=0,cols=0;

*matppm  = (unsigned char )malloc(640*480*3);
  read_ppm_image("rgb_1.ppm" ,  &rows,  &cols);