5 #ifndef GLVERTEX_PNMFORMAT_H
6 #define GLVERTEX_PNMFORMAT_H
12 inline unsigned char *lglReadPnmImage(
const char *filename,
13 int *width,
int *height,
16 const int maxstr = 100;
20 unsigned char *data, *ptr1, *ptr2;
26 data = lglReadFile(filename, &bytes);
28 if (data == NULL)
return(NULL);
29 if (bytes < 4)
return(NULL);
34 if (sscanf(str,
"P%1d\n", &pnmtype) != 1)
return(NULL);
37 while (*ptr1==
'\n' || *ptr1==
'#')
40 if (++ptr1 >= data+bytes) {free(data);
return(NULL);}
42 if (++ptr1 >= data+bytes) {free(data);
return(NULL);}
45 if (++ptr1 >= data+bytes) {free(data);
return(NULL);}
49 while (*ptr2!=
'\n' && *ptr2!=
' ')
50 if (++ptr2 >= data+bytes) {free(data);
return(NULL);}
51 if (++ptr2 >= data+bytes) {free(data);
return(NULL);}
52 while (*ptr2!=
'\n' && *ptr2!=
' ')
53 if (++ptr2 >= data+bytes) {free(data);
return(NULL);}
54 if (++ptr2 >= data+bytes) {free(data);
return(NULL);}
55 while (*ptr2!=
'\n' && *ptr2!=
' ')
56 if (++ptr2 >= data+bytes) {free(data);
return(NULL);}
57 if (++ptr2 >= data+bytes) {free(data);
return(NULL);}
59 if (ptr2-ptr1 >= maxstr) {free(data);
return(NULL);}
60 memcpy(str, ptr1, ptr2-ptr1);
61 str[ptr2-ptr1] =
'\0';
63 if (sscanf(str,
"%d %d\n%d\n", width, height, &maxval) != 3) {free(data);
return(NULL);}
65 if (*width<1 || *height<1) {free(data);
return(NULL);}
67 if (pnmtype==5 && maxval==255) *components = 1;
68 else if (pnmtype==5 && maxval==65535) *components = 2;
69 else if (pnmtype==6 && maxval==255) *components = 3;
70 else {free(data);
return(NULL);}
72 if (data+bytes != ptr2+(*width)*(*height)*(*components)) {free(data);
return(NULL);}
73 if ((image=(
unsigned char *)malloc((*width)*(*height)*(*components))) == NULL) {free(data);
return(NULL);}
75 memcpy(image, ptr2, (*width)*(*height)*(*components));
81 inline unsigned char *lglReadPnmImage(std::string filename,
82 int *width,
int *height,
85 return(lglReadPnmImage(filename.c_str(),
91 inline bool lglWritePnmImage(
const char *filename,
93 int width,
int height,
98 if (width<1 || height<1)
return(
false);
99 if (components<1 || components>4)
return(
false);
101 if ((file=fopen(filename,
"wb")) == NULL)
return(
false);
103 if (components==1 || components==2) fprintf(file,
"P5");
104 else if (components==3) fprintf(file,
"P6");
105 else if (components==4) fprintf(file,
"P8");
107 fprintf(file,
"\n%d %d\n", width, height);
109 if (components==1 || components==3 || components==4) fprintf(file,
"255\n");
110 else fprintf(file,
"65535\n");
112 if (fwrite(image, width*height*components, 1, file) != 1) {fclose(file);
return(
false);}
118 inline bool lglWritePnmImage(std::string filename,
119 unsigned char *image,
120 int width,
int height,
123 return(lglWritePnmImage(filename.c_str(),