1 // Copyright (2013) Jann Horn <jann@thejh.net>
8 HEADER typedef struct {
9 HEADER int width, height;
10 HEADER unsigned char *data;
14 PUBLIC_FN pnm_image *read_image(char *path) {
18 FILE *f = fopen(path, "r");
20 pnm_image *result = malloc(sizeof(pnm_image));
21 if (!result) { saved_errno = errno; goto out_close; }
26 char *buf = malloc(bufsize);
28 assert(fgets(buf, bufsize, f) == buf);
29 if (buf[0] == '#') continue;
32 if (strcmp(buf, "P6\n")) {
33 saved_errno = ENOEXEC;
40 sscanf(buf, "%i %i", &result->width, &result->height);
41 result->data_size = 3 * result->width * result->height;
42 result->data = malloc(result->data_size);
47 if (strcmp(buf, "255\n")) {
61 assert(fread(result->data, result->data_size, 1, f) == 1);
68 if (saved_errno) errno = saved_errno;
72 PUBLIC_FN int write_image(pnm_image *img, char *outfile) {
73 char outbuf[100+img->data_size];
74 int ob_used = snprintf(outbuf, sizeof(outbuf), "P6\n%d %d\n255\n", img->width, img->height);
75 if (ob_used >= 100) xperror("header size is bigger than anticipated", 0);
76 memcpy(outbuf+ob_used, img->data, img->data_size);
77 return write_file(outfile, outbuf, ob_used+img->data_size, 0);
80 PUBLIC_FN pnm_image *dup_image(pnm_image *img) {
81 pnm_image *r = malloc(sizeof(pnm_image));
84 r->data = malloc(r->data_size);
85 if (!r->data) { free(r); return NULL; }
86 memcpy(r->data, img->data, r->data_size);