labyrinth

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