#include #include #include #include "ppm.h" // based on code from http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file#C #define BMAX 256 ppm_t * ppmread (char *filename) { unsigned char buf[BMAX], *t; FILE *fp = fopen (filename, "r"); char c; int r; int pixels; int i, j, p; ppm_t *image; if (fp == NULL) return NULL; t = (unsigned char *)fgets ((char *)buf, BMAX, fp); if ((t == NULL) || (strncmp ((const char *)buf, "P3\n", 3) != 0)) { fprintf (stderr, "file does not start with 'P3\\n'\n"); return NULL; } while (1) { t = (unsigned char *) fgets ((char *)buf, BMAX, fp); if (*t != '#') break; } image = (ppm_t *) malloc (sizeof (ppm_t)); if (image == NULL) return NULL; image->x = 0; image->y = 0; image->d = 0; r = sscanf ((const char *)buf, "%u %u", &image->x, &image->y); if ( r < 2 ) {free (image); return NULL; } r = fscanf (fp, "%u", &image->d); if ( (r < 1) || ( image->d != 255 ) ) { free (image); return NULL; } pixels = (image->x) * (image->y) * 3; image->rgb = (unsigned char *) malloc (pixels); if (image->rgb == NULL) { free (image); return NULL; } fprintf (stderr, "image '%s' %3d x %3d , depth=%3d\n", filename, image->x, image->y, image->d); if (image->rgb == NULL) return NULL; t = image->rgb; for (i = 0; i < image->x; i++) for (j = 0; j < image->y; j++) for (p = 0; p < 3; p++) { r = fscanf (fp, "%u", t); // fprintf (stderr, "pixel[%3d][%3d]=%3u\n", i, j, *t); if (r != 1) return NULL; t++; } return image; } int ppmwrite (char *filename, ppm_t *image) { FILE *fp = fopen (filename, "w"); int i, j, p; unsigned char *t; fprintf (fp, "P3\n%u %u\n%u\n", image->x, image->y, image->d); t = image->rgb; for (i = 0; i < image->x; i++) { for (j = 0; j < image->y; j++) { for (p = 0; p < 3; p++) { fprintf (fp, "%u ", *t); t++; } fprintf (fp, " "); } fprintf (fp, "\n"); } } void ppmfree (ppm_t *image) { free (image->rgb); free (image); } ppm_t * ppmalloc (int x, int y, int d) { ppm_t *image = (ppm_t *) malloc (sizeof (ppm_t)); if (image == NULL) return NULL; image->x = x; image->y = y; image->d = d; image->rgb = (unsigned char *) malloc (x * y * 3); if (image->rgb == NULL) { free (image); return NULL; } return image; } /* int main (int argc, char *argv[]) { unsigned int x, y, d; char *fn = "Untitled.ppm"; ppm_t *image; image = ppmread (fn); ppmwrite ("out.ppm", image); return; } */