1
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <math.h>
6
7 #include <ming_config.h>
8
9 #include <gif_lib.h>
10 #include <zlib.h>
11
12 #include "libming.h"
13
14 #define max3(a,b,c) (((a)>(b))?(((c)>(a))?(c):(a)):(((c)>(b))?(c):(b)))
15
error(char * msg,int errorCode)16 void error(char *msg, int errorCode)
17 {
18 printf("%s:\n\n", msg);
19 PrintGifError(errorCode);
20 exit(-1);
21 }
22
readGif(char * fileName,int * length)23 unsigned char *readGif(char *fileName, int *length)
24 {
25 GifFileType *file;
26 unsigned char *bits;
27 unsigned char colorMap[256];
28 unsigned char *data;
29 int i, nColors, size;
30
31 #if GIFLIB_MAJOR < 5
32 if((file = DGifOpenFileName(fileName)) == NULL)
33 error("Error opening file", 0);
34 #else
35 int errorCode = 0;
36
37 if((file = DGifOpenFileName(fileName, &errorCode)) == NULL)
38 error("Error opening file", errorCode);
39 #endif
40
41 if(DGifSlurp(file) != GIF_OK)
42 #if GIFLIB_MAJOR < 5
43 error("Error slurping file", 0);
44 #else
45 error("Error slurping file", file->Error);
46 #endif
47
48 /* data should now be available */
49
50 nColors = file->SColorMap->ColorCount;
51
52 for(i=0; i<nColors; ++i)
53 {
54 GifColorType c = file->SColorMap->Colors[i];
55
56 colorMap[i] = max3(c.Blue, c.Red, c.Green);
57 }
58
59 bits = file->SavedImages[0].RasterBits;
60
61 size = file->SWidth * file->SHeight;
62 data = malloc(size);
63
64 for(i=0; i<size; ++i)
65 data[i] = colorMap[(unsigned char)bits[i]];
66
67 *length = size;
68
69 return data;
70 }
71
usage()72 void usage()
73 {
74 printf("gif2mask - convert a gif image to an alpha mask\n");
75 printf("\nusage: gif2mask <file.gif>\n");
76
77 exit(0);
78 }
79
main(int argc,char * argv[])80 int main(int argc, char *argv[])
81 {
82 int len, size;
83 unsigned long outsize;
84 char *outfile;
85 unsigned char *data, *outdata;
86 FILE *mask;
87
88 if(argc < 2)
89 usage();
90
91 len = strlen(argv[1]);
92
93 if(strcmp(argv[1]+len-4, ".gif") != 0)
94 usage();
95
96 outfile = strdup(argv[1]);
97
98 outfile[len-3] = 'm';
99 outfile[len-2] = 's';
100 outfile[len-1] = 'k';
101
102 data = readGif(argv[1], &size);
103
104 outdata = malloc(outsize = (int)floor(size*1.01+12));
105
106 /* zlib-compress the gif data */
107 compress2(outdata, &outsize, data, size, 9);
108
109 /* outsize = size; */
110 /* Let's better use the compress2() result value */
111 /* of compressed data size instead using original size */
112 /* else we would waste some outdata file space -- ak'09 */
113
114 /* dump to outfile */
115
116 mask = fopen(outfile, "wb");
117
118 if(fwrite(outdata, sizeof(char), outsize, mask) != outsize)
119 {
120 printf("Didn't write all of the file!");
121 exit(-1);
122 }
123
124 exit(0);
125 }
126