2 * Thanks to Simon who contributed the code to make these functions
15 int eat_ws_comments(FILE *fp
)
19 while ((c
= fgetc(fp
)) != EOF
) {
20 if (c
== '#') { /* eat the comment */
23 if (c
== EOF
) /* but bail if we hit EOF */
28 if (!isspace(c
)) { /* we are done */
33 return -1; /* fell out of the loop */
37 /* this is a kludge, but raw pnm's are not well defined... */
39 int eat_ws_to_eol (FILE *fp
)
46 if (c
== '\n' || c
== '\r') /* some dos/win pnms generated with */
47 return c
; /* just '\r' after maxval */
55 int read_pnm_header_internal (FILE *fp
, int *w
, int *h
)
62 type
= fgetc(fp
) - '0';
64 if (type
< 0 || type
> 6)
65 return -1; /* invalid type */
74 fscanf(fp
, "%d", &maxval
);
81 int read_pnm_header (char *fname
, int *w
, int *h
)
84 FILE *fp
= fopen(fname
, "rb");
89 type
= read_pnm_header_internal (fp
, w
, h
);
93 return (type
== 3 || type
== 6) ? 3 : 1;
97 int read_pnm (char *fname
, uint8_t *buf
)
99 FILE *fp
= fopen(fname
, "rb");
106 type
= read_pnm_header_internal (fp
, &w
, &h
);
110 if (fread (buf
, 1, w
*h
, fp
) != w
*h
)
114 if (fread (buf
, 3, w
*h
, fp
) != w
*h
)
118 fprintf (stderr
, "%s: unimplemented image format !!!\n", __FUNCTION__
);
127 void write_pnm (char *fname
, uint8_t *rgb
, int w
, int h
)
131 outfile
= fopen (fname
, "wb");
134 fprintf (stderr
, "error opening '%s' for writing !!!\n", fname
);
139 if (strstr(fname
, ".ppm") == fname
+ strlen(fname
)-4) {
140 fprintf (outfile
, "P6\n%d %d\n%d\n", w
, h
, 255);
141 fwrite (rgb
, 3, w
*h
, outfile
);
142 } else if (strstr(fname
, ".pgm") == fname
+ strlen(fname
)-4) {
143 fprintf (outfile
, "P5\n%d %d\n%d\n", w
, h
, 255);
144 fwrite (rgb
, 1, w
*h
, outfile
);
147 "%s: can't write anything else than .ppm's and .pgm's !\n",
157 uint8_t CLAMP(int16_t x
)
159 return ((x
> 255) ? 255 : (x
< 0) ? 0 : x
);
163 void write_pgm16 (char *fname
, int16_t *rgb
, int w
, int h
, int16_t offset
)
168 outfile
= fopen (fname
, "wb");
171 printf ("error opening '%s' for writing !!!\n", fname
);
175 fprintf (outfile
, "P5\n%d %d\n%d\n", w
, h
, 255);
176 for (i
=0; i
<w
*h
; i
++) {
177 uint8_t c
= CLAMP(rgb
[i
] + offset
);
178 fwrite (&c
, 1, 1, outfile
);