labyrinth

annotate src/image.c @ 6:345db647383a

fixed the unloadable so bug
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 03 May 2015 02:23:54 +0300
parents
children
rev   line source
nuclear@0 1 #include <stdio.h>
nuclear@0 2 #include <stdlib.h>
nuclear@0 3 #include <string.h>
nuclear@0 4 #include <errno.h>
nuclear@0 5 #include "image.h"
nuclear@0 6
nuclear@0 7 struct image *load_image(const char *fname)
nuclear@0 8 {
nuclear@0 9 FILE *fp;
nuclear@0 10 int i, hdrline = 0;
nuclear@0 11 struct image *img = 0;
nuclear@0 12
nuclear@0 13 if(!(fp = fopen(fname, "rb"))) {
nuclear@0 14 fprintf(stderr, "failed to open pixmap: %s: %s\n", fname, strerror(errno));
nuclear@0 15 return 0;
nuclear@0 16 }
nuclear@0 17
nuclear@0 18 if(!(img = malloc(sizeof *img))) {
nuclear@0 19 perror("failed to allocate image structure");
nuclear@0 20 goto err;
nuclear@0 21 }
nuclear@0 22
nuclear@0 23 /* read ppm header */
nuclear@0 24 while(hdrline < 3) {
nuclear@0 25 char buf[64];
nuclear@0 26
nuclear@0 27 if(!fgets(buf, sizeof buf, fp)) {
nuclear@0 28 goto err;
nuclear@0 29 }
nuclear@0 30
nuclear@0 31 /* skip comments */
nuclear@0 32 if(buf[0] == '#')
nuclear@0 33 continue;
nuclear@0 34
nuclear@0 35 switch(hdrline++) {
nuclear@0 36 case 0:
nuclear@0 37 /* first header line should be P6 */
nuclear@0 38 if(strcmp(buf, "P6\n") != 0) {
nuclear@0 39 goto err;
nuclear@0 40 }
nuclear@0 41 break;
nuclear@0 42
nuclear@0 43 case 1:
nuclear@0 44 /* second header line contains the pixmap dimensions */
nuclear@0 45 if(sscanf(buf, "%d %d", &img->width, &img->height) != 2) {
nuclear@0 46 goto err;
nuclear@0 47 }
nuclear@0 48 break;
nuclear@0 49 }
nuclear@0 50 }
nuclear@0 51
nuclear@0 52 /* allocate the image (each pixel is 3 bytes r, g, and b) */
nuclear@0 53 if(!(img->pixels = malloc(img->width * img->height * 3))) {
nuclear@0 54 goto err;
nuclear@0 55 }
nuclear@0 56
nuclear@0 57 /* read all pixels */
nuclear@0 58 for(i=0; i<img->width * img->height * 3; i++) {
nuclear@0 59 int c = fgetc(fp);
nuclear@0 60 if(c < 0) {
nuclear@0 61 goto err;
nuclear@0 62 }
nuclear@0 63 img->pixels[i] = c;
nuclear@0 64 }
nuclear@0 65 fclose(fp);
nuclear@0 66
nuclear@0 67 return img;
nuclear@0 68
nuclear@0 69 err:
nuclear@0 70 fprintf(stderr, "failed to load pixmap: %s\n", fname);
nuclear@0 71 if(img) {
nuclear@0 72 free(img->pixels);
nuclear@0 73 free(img);
nuclear@0 74 }
nuclear@0 75 if(fp) {
nuclear@0 76 fclose(fp);
nuclear@0 77 }
nuclear@0 78 return 0;
nuclear@0 79 }
nuclear@0 80
nuclear@0 81
nuclear@0 82 void free_image(struct image *img)
nuclear@0 83 {
nuclear@0 84 if(img) {
nuclear@0 85 free(img->pixels);
nuclear@0 86 free(img);
nuclear@0 87 }
nuclear@0 88 }