File: gif2png.c

package info (click to toggle)
gif2png 0.6-1
  • links: PTS
  • area: non-free
  • in suites: slink
  • size: 152 kB
  • ctags: 137
  • sloc: ansic: 1,319; makefile: 62; sh: 17
file content (646 lines) | stat: -rw-r--r-- 17,002 bytes parent folder | download
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
/*
 * gif2png.c
 * Copyright (C) 1995 Alexander Lehmann
 * For conditions of distribution and use, see copyright notice in gif2png.h
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define PNG_INTERNAL
#include "gif2png.h"

struct GIFelement first={NULL};
struct GIFelement *current;
int delete;
int histogram;
int interlaced;
int progress;
int recover;
int software_chunk;
int skip_pte;

/* return the actual line # used to store an interlaced line */

int interlace_line(int height, int line)
{
  int res;

  if((line&7)==0) {
    return line>>3;
  }
  res=(height+7)>>3;
  if((line&7)==4) {
    return res+((line-4)>>3);
  }
  res+=(height+3)>>3;
  if((line&3)==2) {
    return res+((line-2)>>2);
  }
  return res+((height+1)>>2)+((line-1)>>1);
}

/* inverse function of above, used for recovery of interlaced images */

int inv_interlace_line(int height, int line)
{
  if((line<<3)<height) {
    return line<<3;
  }
  line-=(height+7)>>3;
  if((line<<3)+4<height) {
    return (line<<3)+4;
  }
  line-=(height+3)>>3;
  if((line<<2)+2<height) {
    return (line<<2)+2;
  }
  line-=(height+1)>>2;
  return (line<<1)+1;
}

/* do some adjustments of the color palette. We won't check for duplicate
   colors, this is probably only a very rare case, but we check if all used
   colors are grays, some GIF writers (e.g. some versions to ppmtogif) leave
   the unused entries uninitialized, which breaks the detection of grayscale
   images (e.g. in QPV). If the image is grayscale we will use color type 0,
   except when the transparency color is also appearing as a visible color. In
   this case we write a paletted image, another solution would be gray+alpha,
   but that would probably increase the image size too much.
   If there are only few gray levels (<=16), we try to create a 4 or less bit
   grayscale file, but if the gray levels do not fit into the necessary grid,
   we write a paletted image, e.g. if the image contains black, white and 50%
   gray, the grayscale image would require 8 bit, but the paletted image only
   2 bit. Even with filtering, the 8 bit file will be larger.
*/

int graycheck(png_color c)
{
  /* check if r==g==b, moved to function to work around NeXTstep 3.3 cc bug.
   * life could be so easy if at least the basic tools worked as expected.
   */
  return c.red==c.green && c.green==c.blue;
}

int writefile(struct GIFelement *s, struct GIFelement *e, FILE *fp, int lastimg)
{
  int i;
  struct GIFimagestruct *img=e->imagestruct;
  unsigned long *count=img->color_count;
  GifColor *colors=img->colors;
  int gray;
  int last_color=0, colors_used=0;
  byte remap[MAXCMSIZE];
  int low_presc;
  png_struct *png_ptr = xalloc(sizeof (png_struct));
  png_info *info_ptr = xalloc(sizeof (png_info));
  int p;
  int bitdepth, gray_bitdepth;
  png_byte pal_trans[MAXCMSIZE];
  png_color_16 color16trans, color16back;
  byte buffer[24]; /* used for gIFt and gIFg */
  byte *data;
  int j;
  png_uint_16 histogr[MAXCMSIZE];
  unsigned long hist_maxvalue;
  int passcount;
  png_text software;

  if(img->trans!=-1 && !count[img->trans])
    img->trans=-1;

  gray=1;

  for(i=0;i<MAXCMSIZE;i++)
    if(count[i]) {
      gray &= graycheck(colors[i]);
      colors_used++;
      if(last_color<i) last_color=i;
    }

  if(gray) {
    fprintf(stderr, "image is grayscale\n");

    /* zero out unused colors */

    for(i=0;i<MAXCMSIZE;i++)
      if(!count[i]) {
        colors[i].red=colors[i].green=colors[i].blue=0;
      }

    if(img->trans!=-1) {
      for(i=0;i<MAXCMSIZE;i++) {
        if(i!=img->trans && colors[i].red==colors[img->trans].red) {
          gray=0;
          fprintf(stderr, "trans color is repeated in visible colors, using palette\n");
          break;
        }
      }
    }
  }

  bitdepth=8;
  if(last_color<16) bitdepth=4;
  if(last_color<4) bitdepth=2;
  if(last_color<2) bitdepth=1;

  if(gray) {
    for(i=0;i<MAXCMSIZE;i++)
      remap[i]=colors[i].red;
  }

  if(gray) {
    gray_bitdepth=8;

    /* try to adjust to 4 bit prescision grayscale */

    low_presc=1;
    for(i=0;i<MAXCMSIZE;i++) {
      if((remap[i]&0xf)*0x11!=remap[i]) {
        low_presc=0;
        break;
      }
    }
    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        remap[i] &= 0xf;
      }
      gray_bitdepth=4;
    }

    /* try to adjust to 2 bit prescision grayscale */

    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        if((remap[i]&3)*5!=remap[i]) {
          low_presc=0;
          break;
        }
      }
    }

    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        remap[i] &= 3;
      }
      gray_bitdepth=2;
    }

    /* try to adjust to 1 bit prescision grayscale */

    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        if((remap[i]&1)*3!=remap[i]) {
          low_presc=0;
          break;
        }
      }
    }
    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        remap[i] &= 1;
      }
      gray_bitdepth=1;
    }

    if(bitdepth<gray_bitdepth) {
      gray=0; /* write palette file */
    } else {
      bitdepth=gray_bitdepth;
    }
  }

  fprintf(stderr, "%d colors used, highest color %d, %s, bitdepth %d\n", colors_used, last_color, gray ? "gray":"palette", bitdepth);

  if(setjmp(png_ptr->jmpbuf)) {
    fprintf(stderr, "setjmp returns error condition\n");

    free(png_ptr);
    free(info_ptr);

    return 1;
  }

  png_write_init(png_ptr);
  png_info_init(info_ptr);
  png_init_io(png_ptr, fp);
  info_ptr->width=current->imagestruct->width;
  info_ptr->height=current->imagestruct->height;
  info_ptr->bit_depth=bitdepth;
  info_ptr->color_type=gray ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_PALETTE;
  info_ptr->interlace_type=interlaced;

  if(GifScreen.AspectRatio!=0 && GifScreen.AspectRatio!=49) {
    info_ptr->x_pixels_per_unit=GifScreen.AspectRatio+15;
    info_ptr->y_pixels_per_unit=64;
    info_ptr->phys_unit_type=PNG_RESOLUTION_UNKNOWN;
    info_ptr->valid |= PNG_INFO_pHYs;
  }

  if(img->offset_x>0 && img->offset_y>0) {
    info_ptr->x_offset=img->offset_x;
    info_ptr->y_offset=img->offset_y;
    info_ptr->offset_unit_type=PNG_OFFSET_PIXEL;
    info_ptr->valid |= PNG_INFO_oFFs;
  }

  if(GifScreen.Background>0) { /* no background for palette entry 0 */
    /* if the backgroup color doesn't appear in local palette, we just
       leave it out, if the pic is part of an animation, at least some will
       use the global palette */

    if(gray) {
      if(graycheck(GifScreen.ColorMap[GifScreen.Background])) {
        color16back.gray=remap[GifScreen.Background];
        info_ptr->background=color16back;
        info_ptr->valid |= PNG_INFO_bKGD;
      }
    } else {
      for(i=0;i<MAXCMSIZE;i++) {
        if(GifScreen.ColorMap[GifScreen.Background].red==colors[i].red &&
           GifScreen.ColorMap[GifScreen.Background].green==colors[i].green &&
           GifScreen.ColorMap[GifScreen.Background].blue==colors[i].blue) {
          if(last_color<i) last_color=i;
          color16back.index=i;
          info_ptr->background=color16back;
          info_ptr->valid |= PNG_INFO_bKGD;
          break;
        }
      }
    }
  }

  if(img->trans != -1) {
    if(gray) {
      color16trans.gray=remap[img->trans];
      info_ptr->trans_values=color16trans;
    } else {
      for(i=0;i<MAXCMSIZE;i++) pal_trans[i]=255;
      pal_trans[img->trans]=0;
      info_ptr->trans=pal_trans;
      info_ptr->num_trans=img->trans+1;
    }
    info_ptr->valid |= PNG_INFO_tRNS;
  }

  if(!gray) {
    info_ptr->palette=current->imagestruct->colors;
    info_ptr->num_palette=last_color+1;
    info_ptr->valid |= PNG_INFO_PLTE;
  }

  if(histogram && !gray) {
    /* histogram are not supported for grayscale images */
    hist_maxvalue=0;
    for(i=0;i<MAXCMSIZE;i++)
      if(count[i]>hist_maxvalue)
        hist_maxvalue=count[i];
    if(hist_maxvalue<=65535) {
      /* no scaling necessary */
      for(i=0;i<MAXCMSIZE;i++)
        histogr[i]=(png_uint_16)count[i];
    } else {
      for(i=0;i<MAXCMSIZE;i++)
        if(count[i]) {
          histogr[i]=(png_uint_16)
#ifdef __GO32__
          /* avoid using fpu instructions on djgpp, so we don't need emu387 */
                                   (((long long)count[i]*65535)/hist_maxvalue);
#else
                                   ((double)count[i]*65535.0/hist_maxvalue);
#endif
          if(histogr[i]==0)
            histogr[i]=1;
        } else {
          histogr[i]=0;
        }
    }
    info_ptr->hist=histogr;
    info_ptr->valid |= PNG_INFO_hIST;
  }

  if(software_chunk) {
    software.compression=-1;
    software.key="Software";
    software.text=(char*)version;
    software.text_length=strlen(software.text);

    info_ptr->num_text=1;
    info_ptr->max_text=1;
    info_ptr->text=&software;
  }

  png_write_info(png_ptr, info_ptr);

  info_ptr->num_text=0;
  info_ptr->max_text=0;
  info_ptr->text=NULL;

  if(info_ptr->bit_depth<8)
    png_set_packing(png_ptr);

  /* loop over elements until we reach the image or the last element if
     this is the last image in a GIF */

  while(lastimg ? s!=NULL : s != e->next) {
    switch((byte)s->GIFtype) {
      case GIFimage:
        passcount=png_set_interlace_handling(png_ptr);
        for(p=0;p<passcount;p++)
          for(i=0;i<current->imagestruct->height;i++) {
            if(progress) {
              if(passcount>1)
                printf("%d/%d ", p+1, passcount);
              printf("%2d%%\r", (int)(((long)i*100)/current->imagestruct->height));
              fflush(stdout);
            }
            data=access_data(current, (long) (img->interlace ?
                             interlace_line(current->imagestruct->height,i) : i) *
                             current->imagestruct->width,
                             current->imagestruct->width);
#ifndef TMPFILE
            /* if we store the image in memory, we have to remap once */
            if(gray && p==0) {
#else
            /* if we store the image in a file, we have to remap each time */
            if(gray) {
#endif
              for(j=0;j<img->width;j++) {
                data[j]=remap[data[j]];
              }
            }
            png_write_row(png_ptr, data);
          }
        break;

      case GIFcomment:
        data=access_data(s, 0, s->size);
        if(s->size<500) {
          png_write_tEXt(png_ptr, "Comment", data, s->size);
        } else {
          png_write_zTXt(png_ptr, "Comment", data, s->size, 0);
        }
        break;

      case GIFapplication:
        data=access_data(s, 0, s->size);
        png_write_chunk_start(png_ptr, "gIFx", s->size);
        png_write_chunk_data(png_ptr, data, s->size);
        png_write_chunk_end(png_ptr);
        break;

/* Plain Text Extensions are currently not support due to an unresolved issue
   about transparency. Since there are practically no GIFs around that use
   this, this will not be a problem, but a future version of this program
   will probably support PTEs in full.
*/
#if 0
      case GIFplaintext:
        data=access_data(s, 0, s->size);
        /* gIFt is 12 bytes longer than GCE, due to 32 bit ints and
           rgb colors */
        png_write_chunk_start(png_ptr, "gIFt", s->size+12);
        memset(buffer, 0, 24);
        buffer[2]=data[1];
        buffer[3]=data[0];
        buffer[6]=data[3];
        buffer[7]=data[2];
        buffer[10]=data[5];
        buffer[11]=data[4];
        buffer[14]=data[7];
        buffer[15]=data[6];
        buffer[16]=data[8];
        buffer[17]=data[9];
        buffer[18]=GifScreen.ColorMap[data[10]].red;
        buffer[19]=GifScreen.ColorMap[data[10]].green;
        buffer[20]=GifScreen.ColorMap[data[10]].blue;
        buffer[21]=GifScreen.ColorMap[data[11]].red;
        buffer[22]=GifScreen.ColorMap[data[11]].green;
        buffer[23]=GifScreen.ColorMap[data[11]].blue;
        png_write_chunk_data(png_ptr, buffer, 24);
        png_write_chunk_data(png_ptr, data+12, s->size-12);
        png_write_chunk_end(png_ptr);
        break;
#endif

      case GIFgraphicctl:
        data=access_data(s, 0, s->size);
        buffer[0]=(data[0]>>2)&7;
        buffer[1]=(data[0]>>1)&1;
        buffer[2]=data[2];
        buffer[3]=data[1];

        png_write_chunk(png_ptr, "gIFg", buffer, 4);
        break;

      default:
        fprintf(stderr, "gif2png internal error: encountered unused element type %c\n", s->GIFtype);
        break;
      }
    s=s->next;
  }
  png_write_end(png_ptr, info_ptr);
  png_write_destroy(png_ptr);

  free(png_ptr);
  free(info_ptr);

  return 0;
}

int processfile(char *fname, FILE *fp)
{
  char outname[1025]; /* MAXPATHLEN comes under too many names */
  int num_pics;
  struct GIFelement *start;
  int i;
  char *file_ext;

  if(fp==NULL) return 1;

#ifdef TMPFILE
  fseek(tempfile, 0, SEEK_SET);
#endif

  current=&first;

  num_pics=ReadGIF(fp);

  fclose(fp);

  if(num_pics>=0)
    printf("number of images %d\n", num_pics);

  if(num_pics<=0) return 1;

  /* create output filename */

  strcpy(outname, fname);

  file_ext=outname+strlen(outname)-4;
  if(strcmp(file_ext, ".gif")!=0 && strcmp(file_ext, ".GIF")!=0 &&
     strcmp(file_ext, "_gif")!=0 && strcmp(file_ext, "_GIF")!=0) {
    /* try to derive basename */
    file_ext=outname+strlen(outname);
    while(file_ext>=outname) {
      if(*file_ext=='.' || *file_ext=='/' || *file_ext=='\\') break;
      file_ext--;
    }
    if(file_ext<outname || *file_ext!='.') {
      /* as a last resort, just add .png to the filename */
      file_ext=outname+strlen(outname);
    }
  }

  strcpy(file_ext, ".png"); /* images are named .png, .p01, .p02, ... */

  start=NULL;

  i=0;

  for(current=first.next; current ; current=current->next) {
    if(start==NULL) start=current;
    if(current->GIFtype==GIFimage) {
      i++;
      if((fp=fopen(outname, "wb"))==NULL) {
        perror(outname);
        return 1;
      } else {
        writefile(start, current, fp, i==num_pics);
        fclose(fp);
        start=NULL;
        sprintf(file_ext, ".p%02d", i);
      }
    }
  }

  free_mem();

  if(delete) {
    /* we'll rename the GIF file, maybe a release version of this program will
       actually delete the file */
    strcpy(outname, fname);
    outname[strlen(outname)-1]='_';
    rename(fname, outname);
  }

  return 0;
}

/* check if stdin is a terminal, if your compiler is lacking isatty or fileno
   (non-ANSI functions), just return 0
*/

int input_is_terminal(void)
{
  return isatty(fileno(stdin));
}

int main(int argc, char *argv[])
{
  FILE *fp;
  int i;
  int errors=0;
  char name[1025];
  int ac;

  fprintf(stderr, "%s %s\n", version, compile_info);

#ifdef TMPFILE
  if((tempfile=tmpfile())==NULL) {
    perror("tempfile");
    exit(1);
  }
#endif

  software_chunk=1;
  progress=1;

  ac=1;

  for(ac=1; ac<argc && argv[ac][0]=='-'; ac++)
    for(i=1;i<strlen(argv[ac]);i++)
      switch(argv[ac][i]) {
        case 'd':
          delete=1;
          break;

        case 'h':
          histogram=1;
          break;

        case 'i':
          interlaced=1;
          break;

        case 'p':
          progress=0;
          break;

        case 'r':
          recover=1;
          break;

        case 's':
          software_chunk=0;
          break;

        case 't':
          skip_pte=1;
          break;

        default:
          fprintf(stderr, "unknown option char `%c'\n", argv[ac][i]);
usage:
          fprintf(stderr,
"usage: gif2png [ -dhi ] [file[.gif]] ...\n"
"\n"
"       -d delete source GIF files after successful conversion\n"
"       -i create interlaced PNG files\n"
"       -h create histogram chunks for color files\n"
"       -p do not display progress of PNG writing in %%\n"
"       -r try to recover corrupt GIF files\n"
"       -s do not write Software chunk\n"
"       -t ignore Plain Text Extensions\n"
"\n"
"       if no source files are listed, stdin is converted to noname.png\n"
"       (may not work on systems that distinguish between text and binary mode)\n"
"\n"
"       gif2png is Copyright 1995 by Alexander Lehmann <alex@hal.rhein-main.de>\n"
"       For copyright, license, credits, etc. see the file README, which you\n"
"       should have received along with this program. If you didn't, you may be\n"
"       able to find gif2png on ftp://ftp.uu.net/graphics/png or on my\n"
"       WWW-page http://www.student.informatik.th-darmstadt.de/~alexlehm/\n"
          );
          return 1;
      }

  /* loop over arguments or use stdin */
  if(argc==ac) {
    if(input_is_terminal()) {
      goto usage;
    }
    printf("stdin:\n");
    processfile("noname.gif", stdin);
  } else {
    for(i=ac;i<argc;i++) {
      strcpy(name, argv[i]);
      if((fp=fopen(name, "rb"))==NULL) {
        /* retry with .gif appended */
        strcat(name, ".gif");
        fp=fopen(name,"rb");
      }
      if(fp==NULL) {
        perror(argv[i]);
        errors=1;
      } else {
        printf("%s:\n", name);
        errors |= processfile(name, fp);
        /* fp is closed in processfile */
      }
    }
  }

  return errors;
}