labyrinth

diff src/image.c @ 0:8ba79034e8a6

labyrinth example initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 15 Jan 2015 14:59:38 +0200
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/image.c	Thu Jan 15 14:59:38 2015 +0200
     1.3 @@ -0,0 +1,88 @@
     1.4 +#include <stdio.h>
     1.5 +#include <stdlib.h>
     1.6 +#include <string.h>
     1.7 +#include <errno.h>
     1.8 +#include "image.h"
     1.9 +
    1.10 +struct image *load_image(const char *fname)
    1.11 +{
    1.12 +	FILE *fp;
    1.13 +	int i, hdrline = 0;
    1.14 +	struct image *img = 0;
    1.15 +
    1.16 +	if(!(fp = fopen(fname, "rb"))) {
    1.17 +		fprintf(stderr, "failed to open pixmap: %s: %s\n", fname, strerror(errno));
    1.18 +		return 0;
    1.19 +	}
    1.20 +
    1.21 +	if(!(img = malloc(sizeof *img))) {
    1.22 +		perror("failed to allocate image structure");
    1.23 +		goto err;
    1.24 +	}
    1.25 +
    1.26 +	/* read ppm header */
    1.27 +	while(hdrline < 3) {
    1.28 +		char buf[64];
    1.29 +
    1.30 +		if(!fgets(buf, sizeof buf, fp)) {
    1.31 +			goto err;
    1.32 +		}
    1.33 +
    1.34 +		/* skip comments */
    1.35 +		if(buf[0] == '#')
    1.36 +			continue;
    1.37 +
    1.38 +		switch(hdrline++) {
    1.39 +		case 0:
    1.40 +			/* first header line should be P6 */
    1.41 +			if(strcmp(buf, "P6\n") != 0) {
    1.42 +				goto err;
    1.43 +			}
    1.44 +			break;
    1.45 +
    1.46 +		case 1:
    1.47 +			/* second header line contains the pixmap dimensions */
    1.48 +			if(sscanf(buf, "%d %d", &img->width, &img->height) != 2) {
    1.49 +				goto err;
    1.50 +			}
    1.51 +			break;
    1.52 +		}
    1.53 +	}
    1.54 +
    1.55 +	/* allocate the image (each pixel is 3 bytes r, g, and b) */
    1.56 +	if(!(img->pixels = malloc(img->width * img->height * 3))) {
    1.57 +		goto err;
    1.58 +	}
    1.59 +
    1.60 +	/* read all pixels */
    1.61 +	for(i=0; i<img->width * img->height * 3; i++) {
    1.62 +		int c = fgetc(fp);
    1.63 +		if(c < 0) {
    1.64 +			goto err;
    1.65 +		}
    1.66 +		img->pixels[i] = c;
    1.67 +	}
    1.68 +	fclose(fp);
    1.69 +
    1.70 +	return img;
    1.71 +
    1.72 +err:
    1.73 +	fprintf(stderr, "failed to load pixmap: %s\n", fname);
    1.74 +	if(img) {
    1.75 +		free(img->pixels);
    1.76 +		free(img);
    1.77 +	}
    1.78 +	if(fp) {
    1.79 +		fclose(fp);
    1.80 +	}
    1.81 +	return 0;
    1.82 +}
    1.83 +
    1.84 +
    1.85 +void free_image(struct image *img)
    1.86 +{
    1.87 +	if(img) {
    1.88 +		free(img->pixels);
    1.89 +		free(img);
    1.90 +	}
    1.91 +}