1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include <gif_lib.h>
#include "meh.h"
struct gif_t{
struct image img;
FILE *f;
GifFileType *gif;
};
static int isgif(FILE *f){
return (getc(f) == 'G' && getc(f) == 'I' && getc(f) == 'F');
}
static struct image *gif_open(FILE *f){
struct gif_t *g;
GifFileType *gif;
rewind(f);
if(!isgif(f))
return NULL;
/* HACK HACK HACK */
rewind(f);
lseek(fileno(f), 0L, SEEK_SET);
#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
if(!(gif = DGifOpenFileHandle(fileno(f), NULL))){
#else
if(!(gif = DGifOpenFileHandle(fileno(f)))){
#endif
/* HACK AND HOPE */
rewind(f);
lseek(fileno(f), 0L, SEEK_SET);
return NULL;
}
g = malloc(sizeof(struct gif_t));
g->f = f;
g->gif = gif;
g->img.bufwidth = gif->SWidth;
g->img.bufheight = gif->SHeight;
g->img.fmt = &giflib;
return (struct image *)g;
}
static int gif_read(struct image *img){
unsigned int i, j = 0;
struct gif_t *g = (struct gif_t *)img;
GifColorType *colormap;
SavedImage *s;
int ret;
if((ret = DGifSlurp(g->gif)) != GIF_OK)
goto error;
s = &g->gif->SavedImages[0];
if(s->ImageDesc.ColorMap)
colormap = s->ImageDesc.ColorMap->Colors;
else if(g->gif->SColorMap)
colormap = g->gif->SColorMap->Colors;
else
goto error;
for(i = 0; i < img->bufwidth * img->bufheight; i++){
unsigned char idx = s->RasterBits[i];
img->buf[j++] = colormap[idx].Red;
img->buf[j++] = colormap[idx].Green;
img->buf[j++] = colormap[idx].Blue;
}
img->state |= LOADED | SLOWLOADED;
return 0;
error:
#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
fprintf(stderr, "GIFLIB: %s\n", GifErrorString(ret));
#elif defined(GIFLIB_MAJOR) && defined(GIFLIB_MINOR) && ((GIFLIB_MAJOR == 4 && GIFLIB_MINOR >= 2) || GIFLIB_MAJOR > 4)
fprintf(stderr, "GIFLIB: %s\n", GifErrorString());
#else
PrintGifError();
#endif
return 1;
}
void gif_close(struct image *img){
struct gif_t *g = (struct gif_t *)img;
DGifCloseFile(g->gif);
fclose(g->f);
}
struct imageformat giflib = {
gif_open,
NULL,
gif_read,
gif_close
};
|