Improve wxImage::LoadImage so that image format in not anymore required
[wxWidgets.git] / src / common / imaggif.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: imaggif.cpp
3 // Purpose: wxGIFHandler
4 // Author: Guillermo Rodriguez Garcia
5 // wxWindows adaptation by Vaclav Slavik
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
8
9 /*
10 We don't put pragma implement in this file because it is already present in
11 src/common/image.cpp
12 */
13
14 // For compilers that support precompilation, includes "wx.h".
15 #include <wx/wxprec.h>
16
17 #ifdef __BORLANDC__
18 #pragma hdrstop
19 #endif
20
21 #ifndef WX_PRECOMP
22 #include "wx/defs.h"
23 #endif
24
25 #include "wx/image.h"
26 #include "wx/wfstream.h"
27 #include "wx/module.h"
28 #include "wx/log.h"
29
30 IMPLEMENT_DYNAMIC_CLASS(wxGIFHandler,wxImageHandler)
31
32 #if wxUSE_STREAMS
33
34 /*
35
36 FOLLOWING CODE IS BY G.R.G. :
37 (except wxInputStream stuff)
38
39 */
40
41 /************************************************************************
42 READGIF.H - Reads a GIF file
43 ------------------------------------------------------------------------
44 Guillermo Rodriguez Garcia
45 <guille@iies.es>
46
47 Version: 2.1
48 *************************************************************************/
49
50
51 typedef struct
52 {
53 int w; /* width */
54 int h; /* height */
55 int transparent; /* transparent color (-1 = none) */
56 unsigned char *p; /* bitmap */
57 unsigned char *pal; /* palette */
58 } IMAGEN;
59
60
61
62 /************************************************************************
63 READGIF.C - Reads a GIF file
64 ------------------------------------------------------------------------
65 Guillermo Rodriguez Garcia
66 <guille@iies.es>
67
68 Version: 2.1
69 *************************************************************************/
70
71
72 #include <stdlib.h>
73 #include <string.h>
74
75
76 /* error codes */
77 #define E_OK 0 /* everything was OK */
78 #define E_ARCHIVO -1 /* error opening file */
79 #define E_FORMATO -2 /* error in gif header */
80 #define E_MEMORIA -3 /* error allocating memory */
81
82
83 /* This class binding is by VS, so all bugs in it are mine ;-) */
84
85 class gifDecoder
86 {
87 private:
88 /* globals */
89 int restbits; /* remaining valid bits */
90 unsigned int restbyte; /* remaining bytes in this block */
91 unsigned int lastbyte; /* last byte read */
92
93 wxInputStream *f; /* input file */
94
95 public:
96 gifDecoder(wxInputStream *s) { f = s; }
97 int getcode(int bits);
98 int dgif(IMAGEN *img, int interl, int bits);
99 int readgif(IMAGEN *img);
100 };
101
102
103
104 /* getcode:
105 * Reads the next code from the file, with size 'bits'
106 */
107 int gifDecoder::getcode(int bits)
108 {
109 unsigned int mask; /* bit mask */
110 unsigned int code; /* code (result) */
111
112
113 /* get remaining bits from last byte read */
114 mask = (1 << bits) - 1;
115 code = (lastbyte >> (8 - restbits)) & mask;
116
117 /* keep reading new bytes while needed */
118 while (bits > restbits)
119 {
120 /* if no bytes left in this block, read the next block */
121 if (restbyte == 0)
122 restbyte = (unsigned char)f->GetC();
123
124 /* read next byte and isolate the bits we need */
125 lastbyte = (unsigned char)f->GetC();
126 mask = (1 << (bits - restbits)) - 1;
127 code = code + ((lastbyte & mask) << restbits);
128 restbyte--;
129
130 /* adjust total number of bits extracted from the buffer */
131 restbits = restbits + 8;
132 }
133
134 /* find number of bits reamining for next code */
135 restbits = (restbits - bits);
136
137 return code;
138 }
139
140
141
142 /* dgif:
143 * GIF decoding function. The initial code size (aka root size)
144 * is 'bits'. Supports interlaced images (interl == 1).
145 */
146 int gifDecoder::dgif(IMAGEN *img, int interl, int bits)
147 {
148 int ab_prefix[4096]; /* alphabet (prefixes) */
149 int ab_tail[4096]; /* alphabet (tails) */
150 int stack[4096]; /* decompression stack */
151
152 int ab_clr; /* clear code */
153 int ab_fin; /* end of info code */
154 int ab_bits; /* actual symbol width, in bits */
155 int ab_free; /* first free position in alphabet */
156 int ab_max; /* last possible character in alphabet */
157 int pass; /* pass number in interlaced images */
158 int pos; /* index into decompresion stack */
159 int x, y; /* position in image buffer */
160
161 int code, readcode, lastcode, abcabca;
162
163 /* these won't change */
164 ab_clr = (1 << bits);
165 ab_fin = (1 << bits) + 1;
166
167 /* these will change through the decompression proccess */
168 ab_bits = bits + 1;
169 ab_free = (1 << bits) + 2;
170 ab_max = (1 << ab_bits) - 1;
171 lastcode = -1;
172 abcabca = -1;
173 pass = 1;
174 pos = x = y = 0;
175
176 /* reset static globals */
177 restbits = 0;
178 restbyte = 0;
179 lastbyte = 0;
180
181 do
182 {
183 /* get next code */
184 readcode = code = getcode(ab_bits);
185
186 /* end of image? */
187 if (code == ab_fin) break;
188
189 /* reset alphabet? */
190 if (code == ab_clr)
191 {
192 /* reset main variables */
193 ab_bits = bits + 1;
194 ab_free = (1 << bits) + 2;
195 ab_max = (1 << ab_bits) - 1;
196 lastcode = -1;
197 abcabca = -1;
198
199 /* skip to next code */
200 continue;
201 }
202
203 /* unknown code: special case (like in ABCABCA) */
204 if (code >= ab_free)
205 {
206 code = lastcode; /* take last string */
207 stack[pos++] = abcabca; /* add first character */
208 }
209
210 /* build the string for this code in the stack */
211 while (code > ab_clr)
212 {
213 stack[pos++] = ab_tail[code];
214 code = ab_prefix[code];
215 }
216 stack[pos] = code; /* push last code into the stack */
217 abcabca = code; /* save for special case */
218
219 /* make new entry in alphabet (only if NOT just cleared) */
220 if (lastcode != -1)
221 {
222 ab_prefix[ab_free] = lastcode;
223 ab_tail[ab_free] = code;
224 ab_free++;
225
226 if ((ab_free > ab_max) && (ab_bits < 12))
227 {
228 ab_bits++;
229 ab_max = (1 << ab_bits) - 1;
230 }
231 }
232
233 /* dump stack data to the buffer */
234 while (pos >= 0)
235 {
236 (img->p)[x + (y * (img->w))] = (char)stack[pos--];
237
238 if (++x >= (img->w))
239 {
240 x = 0;
241
242 if (interl)
243 {
244 /* support for interlaced images */
245 switch (pass)
246 {
247 case 1: y += 8; break;
248 case 2: y += 8; break;
249 case 3: y += 4; break;
250 case 4: y += 2; break;
251 }
252 if (y >= (img->h))
253 {
254 switch (++pass)
255 {
256 case 2: y = 4; break;
257 case 3: y = 2; break;
258 case 4: y = 1; break;
259 }
260 }
261 }
262 else
263 {
264 /* non-interlaced */
265 y++;
266 }
267 }
268 }
269
270 pos = 0;
271 lastcode = readcode;
272 }
273 while (code != ab_fin);
274
275 return 0;
276 }
277
278
279
280 /* readgif:
281 * Reads a GIF image from the file with filename 'nombre' in the
282 * IMAGEN structure pointed by 'img'. Can read GIFs with any bit
283 * size (color depth), but the output image is always expanded
284 * to 8 bits per pixel. Also, the image palette always contains
285 * 256 colors, although some of them may be unused. Returns E_OK
286 * (== 0) on success, or an error code if something fails. Error
287 * codes are E_ARCHIVO, E_FORMATO, E_MEMORIA (see above).
288 */
289 int gifDecoder::readgif(IMAGEN *img)
290 {
291 int size, ncolors, bits, interl, i;
292 unsigned char pal[768];
293 unsigned char buf[16];
294
295
296 /* read header and logical screen descriptor block (LSDB) */
297 f->Read(buf, 13);
298
299 /* check GIF signature */
300 if (memcmp(buf, "GIF", 3) != 0) return E_FORMATO;
301
302 /* load global color map if available */
303 if ((buf[10] & 0x80) == 0x80)
304 {
305 ncolors = 2 << (buf[10] & 0x07);
306 f->Read(pal, 3 * ncolors);
307 }
308
309 /* assume no transparent color */
310 img->transparent = -1;
311
312 /* skip most extensions */
313 while (((unsigned char)f->GetC()) == 0x21) /* separator */
314 {
315 if (((unsigned char)f->GetC()) == 0xF9) /* graphic control ext. */
316 {
317 f->Read(buf, 6);
318 if (buf[1] & 0x01)
319 img->transparent = buf[4];
320 }
321 else
322 while ((i = (unsigned char)f->GetC()) != 0) /* byte count */
323 f->SeekI(i, wxFromCurrent);
324 }
325
326 /* read image descriptor block (IDB) */
327 f->Read(buf, 9);
328 img->w = buf[4] + 256 * buf[5];
329 img->h = buf[6] + 256 * buf[7];
330 size = img->w * img->h;
331 interl = ((buf[8] & 0x40)? 1 : 0);
332
333 /* load local color map if available */
334 if ((buf[8] & 0x80) == 0x80)
335 {
336 ncolors = 2 << (buf[8] & 0x07);
337 f->Read(pal, 3 * ncolors);
338 }
339
340 /* get initial code size from first byte in raster data */
341 bits = (unsigned char)f->GetC();
342
343 /* allocate memory for image and palette */
344 if ((img->p = (unsigned char*) malloc(size)) == NULL) return E_MEMORIA;
345 if ((img->pal = (unsigned char*) malloc(768)) == NULL) return E_MEMORIA;
346
347 /* shift palette to fit VGA 6-bit format */
348 for (i = 0; i < 768; i++)
349 (img->pal)[i] = (unsigned char)pal[i]; /* >> 2 not in wxWin */
350
351 /* decode GIF */
352 dgif(img, interl, bits);
353
354 /* finish successfully :-) */
355 return E_OK;
356 }
357
358
359
360 /*
361
362 FOLLOWING CODE IS BY V.S. :
363
364 */
365
366 //-----------------------------------------------------------------------------
367 // wxGIFHandler
368 //-----------------------------------------------------------------------------
369
370 bool wxGIFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool WXUNUSED(verbose) )
371 {
372 unsigned char *ptr, *src, *pal;
373 IMAGEN igif;
374 int i;
375 gifDecoder *decod;
376
377 image->Destroy();
378
379 decod = new gifDecoder(&stream);
380
381 if (decod->readgif(&igif) != E_OK) {
382 wxLogDebug(_T("Error reading GIF"));
383 delete decod;
384 return FALSE;
385 }
386 delete decod;
387
388 image->Create(igif.w, igif.h);
389 if (!image->Ok()) {
390 free(igif.pal);
391 free(igif.p);
392 return FALSE;
393 }
394
395 ptr = image->GetData();
396 src = igif.p;
397 pal = igif.pal;
398
399 if (igif.transparent != -1) {
400 for (i = 0; i < 256; i++)
401 if ((pal[3 * i + 0] == 255) && (pal[3 * i + 1] == 0) && (pal[3 * i + 2] == 255)) pal[3 * i + 2] = 254;
402 pal[3 * (igif.transparent) + 0] = 255,
403 pal[3 * (igif.transparent) + 1] = 0,
404 pal[3 * (igif.transparent) + 2] = 255;
405 image->SetMaskColour(255, 0, 255);
406 }
407 else image->SetMask(FALSE);
408
409 for (i = 0; i < igif.w * igif.h; i++, src++) {
410 *(ptr++) = pal[3 * (*src) + 0];
411 *(ptr++) = pal[3 * (*src) + 1];
412 *(ptr++) = pal[3 * (*src) + 2];
413 }
414
415 free(igif.pal);
416 free(igif.p);
417 return TRUE;
418 }
419
420 bool wxGIFHandler::SaveFile( wxImage * WXUNUSED(image),
421 wxOutputStream& WXUNUSED(stream), bool verbose )
422 {
423 if (verbose) wxLogDebug(_T("wxGIFHandler is read-only!!"));
424 return FALSE;
425 }
426
427 #endif