1 // Copyright (2013) Jann Horn <jann@thejh.net>
9 HEADER typedef struct {
10 HEADER int width, height;
11 HEADER unsigned char *data;
15 PUBLIC_FN pnm_image *read_image(char *path) {
19 FILE *f = fopen(path, "r");
21 pnm_image *result = malloc(sizeof(pnm_image));
22 if (!result) { saved_errno = errno; goto out_close; }
27 char *buf = malloc(bufsize);
29 assert(fgets(buf, bufsize, f) == buf);
30 if (buf[0] == '#') continue;
33 if (strcmp(buf, "P6\n")) {
34 saved_errno = ENOEXEC;
41 sscanf(buf, "%i %i", &result->width, &result->height);
42 result->data_size = 3 * result->width * result->height;
43 result->data = malloc(result->data_size);
48 if (strcmp(buf, "255\n")) {
62 assert(fread(result->data, result->data_size, 1, f) == 1);
69 if (saved_errno) errno = saved_errno;
73 PUBLIC_FN int write_image(pnm_image *img, char *outfile) {
74 char outbuf[100+img->data_size];
75 int ob_used = snprintf(outbuf, sizeof(outbuf), "P6\n%d %d\n255\n", img->width, img->height);
76 if (ob_used >= 100) xperror("header size is bigger than anticipated", 0);
77 memcpy(outbuf+ob_used, img->data, img->data_size);
78 return write_file(outfile, outbuf, ob_used+img->data_size, 0);
81 PUBLIC_FN pnm_image *dup_image(pnm_image *img) {
82 pnm_image *r = malloc(sizeof(pnm_image));
85 r->data = malloc(r->data_size);
86 if (!r->data) { free(r); return NULL; }
87 memcpy(r->data, img->data, r->data_size);