8 #include "color_bits.h"
11 int check_ppm(FILE *fp) {
12 fseek(fp, 0, SEEK_SET);
13 if(fgetc(fp) == 'P' && fgetc(fp) == '6') {
19 static int read_to_wspace(FILE *fp, char *buf, int bsize) {
22 while((c = fgetc(fp)) != -1 && !isspace(c) && count < bsize - 1) {
24 while((c = fgetc(fp)) != -1 && c != '\n' && c != '\r');
26 if(c == '\n' || c == '\r') continue;
33 while((c = fgetc(fp)) != -1 && isspace(c));
38 void *load_ppm(FILE *fp, unsigned long *xsz, unsigned long *ysz) {
41 unsigned int w, h, i, sz;
44 fseek(fp, 0, SEEK_SET);
46 bytes = read_to_wspace(fp, buf, 64);
49 if((bytes = read_to_wspace(fp, buf, 64)) == 0) {
54 fprintf(fp, "load_ppm: invalid width: %s", buf);
60 if((bytes = read_to_wspace(fp, buf, 64)) == 0) {
65 fprintf(fp, "load_ppm: invalid height: %s", buf);
71 if((bytes = read_to_wspace(fp, buf, 64)) == 0) {
75 if(!isdigit(*buf) || atoi(buf) != 255) {
76 fprintf(fp, "load_ppm: invalid or unsupported max value: %s", buf);
81 if(!(pixels = malloc(w * h * sizeof *pixels))) {
82 fputs("malloc failed", fp);
93 if(r == -1 || g == -1 || b == -1) {
96 fputs("load_ppm: EOF while reading pixel data", fp);
99 pixels[i] = PACK_COLOR24(r, g, b);
109 int save_ppm(FILE *fp, void *pixels, unsigned long xsz, unsigned long ysz) {
110 int i, sz = xsz * ysz;
111 uint32_t *ptr = pixels;
113 fprintf(fp, "P6\n%lu %lu\n255\n# 3dengfx PPM file writer\n", xsz, ysz);
115 for(i=0; i<sz; i++) {
116 int r = (*ptr & RED_MASK32) >> RED_SHIFT32;
117 int g = (*ptr & GREEN_MASK32) >> GREEN_SHIFT32;
118 int b = (*ptr++ & BLUE_MASK32) >> BLUE_SHIFT32;
120 if(fputc(r, fp) == EOF || fputc(g, fp) == EOF || fputc(b, fp) == EOF) {
121 fputs("save_ppm: failed to write to file", stderr);
131 #endif /* IMGLIB_USE_PPM */