/* * ppmutil.c: Open PPM file and get size of width and height. * (Only support P6/P5 format file) * * Oct.6.'94. Oshiro. */ #include #include #include #include #include "ppmutils.h" int GetCharIgnoreSpaceAndComment(FILE *fp) { static begin_line=1; int c; while (1) { c=getc(fp); if (begin_line==1) { while (1) { if (!isspace(c) || c=='\n') break; c=getc(fp); } begin_line=0; } if (c=='#') { while ((c=getc(fp))!='\n') ; begin_line=1; continue; } if (c=='\n') begin_line=1; break; } return c; } int GetOneLine(FILE *fp, char *str) { int c; int i; for (i=0; (c=GetCharIgnoreSpaceAndComment(fp))!='\n'; i++) { if (i>=PPMUTILS_CHECK_STR_MAX) { return -1; } str[i]=c; } str[i]='\0'; return 0; } int CheckPPMFile(FILE *fp, int *type, int *width, int *height, int *depth) { char str[PPMUTILS_CHECK_STR_MAX]; int w, h, d; int i, c; if (GetOneLine(fp, str)!=0) return -1; fprintf(stderr, "type:%s", str); if (strcmp(str, "P6")!=0 && strcmp(str, "P5")!=0) return -1; *type=str[1]; if (GetOneLine(fp, str)!=0) return -1; if (sscanf(str, "%d %d", &w, &h)!=2) return -1; if (GetOneLine(fp, str)!=0) return -1; d=atoi(str); if (d<=0 || d>255) return -1; /* if (strcmp(str, "255")!=0) return -1; */ *width=w; *height=h; *depth=d; return 0; } FILE *OpenAndCheckPPMFile(char *fname, int *type, int *width, int *height, int *depth) { FILE *fp; if (fname==NULL) { fp=stdin; } else { fp=fopen(fname, "rb"); if (fp==NULL) return NULL; } if (CheckPPMFile(fp, type, width, height, depth)!=0) { fclose(fp); return NULL; } return fp; } #ifdef PPMUTILS_TEST int main(int argc, char **argv) { FILE *fp; int w, h, d; if (argc==2) { fp=OpenAndCheckPPMFile(argv[1], &w, &h, &d); if (fp==NULL) { fprintf(stderr, "Incorrect PPM file `%s'.\n", argv[1]); exit(-1); } } else { fp=stdin; if (CheckPPMFile(stdin, &w, &h, &d)!=0) { fprintf(stderr, "Incorrect PPM file `%s'.\n", argv[1]); exit(-1); } } printf("ImageSize: %dx%d(%d)\n", w, h, d); return 0; } #endif /* PPMUTILS_TEST */