#include "include.h" #include "ppm.h" int LoadPpmFile(char *filename, PpmImage *ppm) { FILE *stream; char str[256]; int width, height, maxval; unsigned int size; if (!(stream = fopen(filename, "rb"))) { printf("couldn't open file %s\n", filename); return 0; } fgets(str, 256, stream); if (strncmp(str, "P6", 2) && strncmp(str, "P3", 2)) { fclose(stream); printf("bad magic number %s\n", str); return 0; } do { fgets(str, 256, stream); } while (str[0] == '#'); // skip the comments if (sscanf(str, "%d %d", &width, &height) != 2) { fclose(stream); printf("couldn't figure out the size of image %s\n", filename); return 0; } fgets(str, 256, stream); if (sscanf(str, "%d", &maxval) != 1) { fclose(stream); printf("couldn't read maxval of image %s\n", filename); return 0; } if (maxval != 255) { printf("warning: maxval == %d, not 255\n", maxval); } size = 3*width*height; if (!(ppm->data = new unsigned char[size])) { fclose(stream); printf("couldn't allocated memory for the image pixels\n"); return -1; } if (fread(ppm->data, sizeof(unsigned char), size, stream) != size) { fclose(stream); printf("couldn't read the image data for %s\n", filename); return 0; } ppm->width = width; ppm->height = height; if (fclose(stream)) { return 0; } return 1; }