-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGIFIMAGE.PAS
7624 lines (6927 loc) · 219 KB
/
GIFIMAGE.PAS
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit GIFImage;
(*******************************************************************************
********************************************************************************
** **
** Project: GIF Graphics Object **
** Module: gifimage **
** Description: TGraphic implementation of the GIF89a graphics format. **
** Version: 2.0 **
** Release: 3 **
** Date: 26-APR-1998 **
** Target: Win32, Delphi 2 & 3, C++ Builder 3 **
** Author(s): anme: Anders Melander, [email protected] **
** fila: Filip Larsen, [email protected] **
** rps: Reinier Sterkenburg **
** Copyright (c) 1997,98 by Anders Melander **
** Formatting: 2 space indent, 8 space tabs, 80 columns. **
** **
********************************************************************************
********************************************************************************
This software is copyrighted as noted above. It may be freely copied, modified,
and redistributed, provided that the copyright notice(s) is preserved on all
copies.
There is no warranty or other guarantee of fitness for this software, it is
provided solely "as is". Bug reports or fixes may be sent to the author, who
may or may not act on them as he desires.
You may not include this software in a program or other software product without
supplying the source, or without informing the end-user that the source is
available for no extra charge.
If you modify this software, you should include a notice in the "Revision
history" section giving the name of the person performing the modification, the
date of modification, and the reason for such modification.
--------------------------------------------------------------------------------
Here's some additional copyrights for you:
Portions copyright (c) Borland International.
The Graphics Interchange Format(c) is the Copyright property of CompuServe
Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated.
+-------------------------------------------------------------------+
| Copyright 1993, David Koblas ([email protected]) |
| |
| Permission to use, copy, modify, and to distribute this software |
| and its documentation for any purpose is hereby granted without |
| fee, provided that the above copyright notice appear in all |
| copies and that both that copyright notice and this permission |
| notice appear in supporting documentation. There is no |
| representations about the suitability of this software for |
| any purpose. this software is provided "as is" without express |
| or implied warranty. |
| |
+-------------------------------------------------------------------+
Copyright (C) 1989 by Jef Poskanzer.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation. This
software is provided "as is" without express or implied warranty.
COPYRIGHT 1994,1995 BY THE QUEST CENTER AT COLD SPRING HARBOR LABS.
Permission granted for unlimited use, provided that Thomas Boutell and the Quest
Center at Cold Spring Harbor Labs are given credit for the library in the
user-visible documentation of your software. If you modify gd, we ask that you
share the modifications with us so they can be added to the distribution.
See gd.html for details.
--------------------------------------------------------------------------------
Revision history:
0001 120797 anme - Modified GifImage (see credits) to derive from TGraphic.
- Added TPicture registration.
- Added support for stream based (TStream) instead of
file based I/O.
0002 150797 anme - Zapped version 0.01 - it was just too damned slow.
- Version 0.02 is a completely new design rewritten from
scratch from the gif89a specification.
200797 anme - Implemented GIF compressor (see credits).
10-20 times faster that version 0.01 on some images.
fila - Improved hash key generator - Average hit ratio is now
about 5:1 compared to 2:1 for original algorithm.
220797 anme - Optimized compressor hash functions - Average hit
ratio is now about 15:1.
270797 anme - Implemented GIF decompressor (see credits).
Fast'n dirty port of "C" version. Will need to be
optimized and cleaned up at some point.
0100 300797 anme - Implemented TGIFPainter for drawing animated GIFs.
- Implemented TGIFAppExtNSLoop to support Netscape loop
extension.
- Implemented TGIFUnknownAppExtension to support unknown
application extensions.
0101 030897 anme - Added TGIFPainter support for transparent GIFs
Only supported for D3 in this version.
080897 anme - Added TGIFPainter support for Disposal.
110897 anme - Fixed TGIFPainter thread termination on TGIFImage
destruction.
160897 anme - Fixed bug in TGIFSubImage.Assign(TGIFSubImage).
- Added TPicture registration.
- Completed implementation of TGraphic functions.
230897 anme - Improved handling of Paint & Draw options.
- Improved handling of threaded/animated Draw().
271097 anme - Added handling of non-compliant zero-padding between
image blocks.
- sDecodeTooFewBits is now treated as a warning condition
instead of an error.
- Added validation of Color Index for TGIFHeader
BackgroundColorIndex and TGIFGraphicControlExtension
TransparentColorIndex.
Invalid index triggers a sBadColorIndex warning and
sets the index to 0.
- Changed TGIFImage.Paint to draw in main thread if
there is only one sub image.
221197 anme - Fixed bug in TGIFAppExtNSLoop. Signature was not
written to GIF file.
- Changed TGIFImage.Add() to return index of new item.
- Added ability to TGIFColorMap.Optimize to remove
unused palette entries after bitmap import.
- Added check for empty colormap in ExportPalette.
- Added Restart to TGIFPainter for improved performance.
291197 anme - Fixed Access Violation when streaming an empty
TGIFSubImage by improving TGIFSubImage.GetEmpty.
- Added Painters property to TGIFImage to make it
possible to determine if a given painter is still
alive.
- Fixed reentrancy bug in TGIFPainter.Execute that would
corrupt the destination canvas handle under some
obscure circumstances.
061297 anme - Improved handling of Paint executing in main thread.
- Released as beta 0101a.
0102 201297 anme - Added Warning method to TGIFItem and TColorMap to
improve centralized error handling.
This was done to handle invalid Background color index
values in GIFs produced by Microsoft's free GIF
animator tool. The problem was brought to my attention
by Brad Choate - Thanks.
- Removed unused gwsOK and gwOK constants.
- Changed TGIFWarning to procedure of object.
- TGIFImage.Bitmap is now volatile but still public...
- Changed TGIFImage.Draw and Paint completely to draw
indirectly via a TBitmap.
This should eliminate the goAsync problem for Draw.
- Added TGIFImage.StopDraw to stop async Draw.
- Removed potential leak in TGIFPainter.Execute.
If an exception was raised during the extension
preprocessing, the frame buffers would not be freed.
- TGIFImage.Assign can now assign from any TPicture that
can assign to a TBitmap (TPicture->TBitmap->TGIFimage)
271297 anme - Added goDirectDraw option.
goDirectDraw will cause TGIFImage.Draw() to Paint()
directly on the destination canvas instead of via the
bitmap buffer.
- Added TGIFImage.ThreadPriority property.
- Added TGIFImage.DrawBackgroundColor property.
- Added TGIFSubImage.StretchDraw().
- Added TGIFSubImage.ScaleRect().
110198 anme - Misc mods based on feedback from Reinier Sterkenburg.
- Added TGIFList.Image property in order to be able to
report warnings in LoadFromStream.
- TGIFExtensionList.LoadFromStream now handles missing
extension introducers.
Instead of generating an exception, a warning event
is now produced.
- TGIFSubImage.Decompress now handles premature end of
file.
Instead of generating an exception, a warning event
is now produced.
150198 anme - Added TGIFList.Warning to enable graceful recovery
from "bad block type" in TGIFImageList.LoadFromStream.
- Fixed disposal problem in TGIFPainter.DoPaintFrame.
- Added TGIFPainter.DoPaint for non-buffered paint.
220198 anme - Added check for no color tables defined.
Causes a sNoColorTable exception.
- Rewritten palette management.
- Temporarily added DoTransparent parameter to
TGIFSubImage.Draw and StretchDraw until
TBitmap.Transparent problem is fixed.
- Added goLoopContinously to TGIFDrawOptions on request
from Reinier Sterkenburg.
The loop count specified in the GCE will be ignored
if this option is set.
- Added TGIFImage.PaintTryLock.
- Added code in TGIFImage.PaintLock to avoid dead locks.
270198 anme - Added TGIFColorMap.Data property for access to raw
colormap data.
- Added TGIFSubImage.DoGetBitmap and DoGetDitherBitmap.
- Added Floyd Steinberg dithering to TGIFSubImage
GetBitmap via DoGetDitherBitmap (see credits).
- Added goDither to TGIFDrawOptions.
- Fixed goLoopContinously for GIFs without loop ext.
- Modified TGIFApplicationExtension.LoadFromStream
to handle GIFs produced by older Adobe programs.
280198 anme - Fixed bug in TGIFImage.Pack: Only first subimage's
bitmap and palette was zapped.
- Added TGIFSubImage.Mask for better transparency
implementation. Mask is create in DoGet*Bitmap
and used in StretchDraw.
- Copied TransparentStretchBlt from D3 graphics.pas to
implement transparency without TBitmap.Transparent.
050298 anme - Fixed TransparentStretchBlt by using method posted
to borland.public.delphi.vcl.components.writing by
Brian Lowe of Acro Technology Inc. on 30Jan98.
This solved a problem that I must have used at least
60 hours trying to nail.
Thank you to Stefan Hoffmeister for bringing the fix
to my attention.
- Added TGIFSubImage.Transparent read-only property for
better performance.
- Removed PaintLock/PaintUnlock from TGIFImage.Destroy
which caused a dead lock under rare circumstances.
110298 anme - Moved buffer setup from TGIFPainter.Execute to
TGIFPainter.Create.
- Added adjustment of animation delay.
The animation delay now compensates for the time spent
converting the GIF to a bitmap resulting in a more
smooth startup animation.
- Replaced use of Sleep() in threaded paint with
WaitForSingleObject with timeout.
This will enable TGIFPainter.Stop to abort the thread
even though it is waiting for the delay to expire.
- Added TGIFImage.NewBitmap.
- Added buffering of background in TGIFPainter for
transparent paint with dmBackground disposal.
- The goFullDraw option is now obsolete.
- Fixed deadlock problem in TGIFPainter.Stop when
TGIFPainter was running in main thread.
190298 anme - Added goAutoDither option.
The goAutoDither option modifies the behavior of the
goDither option. If goAutoDither is set, the goDither
option will be ignored on displays which supports more
than 256 colors.
- Renamed the goDrawTransparent option to goTransparent.
0105 280298 anme - Fixed loop bug in TGIFPainter.Execute.
Loop would wrap to wrong frame if loop extension
wasn't the first.
- Fixed bug in transparent dmBackground disposal.
Only area covered by previous frame should be
restored - not complete image.
- "Minor" optimizations of TGIFSubImage.Decompress.
- Added progress events to TGIFImage.LoadFromStream
and SaveToStream.
- Released as version 0105.
Even though the last release was version 0101 beta A,
I have decided to bump the version number up to 0105
to reflect the major improvements over the last
release.
Unfortunately this release does still not support
Delphi 2 as promised.
0106 090398 anme - Minor improvement of Progress events in
TGIFImage.LoadFromStream and SaveToStream.
- Added TGIFImageList.SaveToStream method.
- Added Progress events to TGIFImage.Assign.
- Added copy of OnProgress and OnChange properties to
TGIFImage.Assign.
100398 anme - Fixed bug in TGIFPainter.Stop when drawing in main
thread. TGIFPainter object was deleted before Execute
method had finished resulting in access violations.
0200 150398 rps - Ported to Delphi 2.x by Reinier Sterkenburg.
Added support for PixelFormat and ScanLine for Delphi
2.x
Reiniers port will later be merged with the main
source and released as version 2.x.
290398 anme - Added Getters and Setters for TGIFSubImage Left, Top,
Width and Height properties (and various others) for
compatibility with C++ Builder.
C++ Builder does not support properties of the form
property <name>:<type> read <record>.<field> etc.
- Changed some compile time conditions for compatibility
with C++ Builder.
Now uses {$ifndef ver90} instead of {$ifdef ver100} to
check for Delphi 3.x and later.
- Added PixelFormat support for Delphi 2.x with
SetPixelFormat and GetPixelFormat utility functions.
010498 anme - Misc modifications after studying Netscape Mozilla
source code:
* Removed comment about GIFDefaultDelay since the
correct value has now been verified.
* Added GIFMinimumDelay to limit animation speed.
* Added support for ANIMEXTS extension.
* More tolerant load of GIF header.
- Added STRICT_MOZILLA conditional define to disable
non-Mozilla compliant behaviour.
- Ported TGIFSubImage.Assign to Delphi 2:
* Fixed bugs in import of 1 bit/pixel bitmaps.
* Replaced use of TBitmap.Scanline[] and PixelFormat
with internal DIB support functions.
* Fixed bugs in import via TCanvas.Pixels.
- Fixed memory allocation bug in TColorMap.SetCapacity.
Too little memory was being reallocated on resize.
060498 anme - Ported TGIFSubImage.GetXXXBitmap to Delphi 2 by
removing dependancy on TBitmap.ScanLine.
- Added GIFMaximumDelay to replace hardcoded limit
in TGIFPainter.Execute.
- Merged Reinier Sterkenburg's Delphi 2 port with the
main source.
- Added a lot of Delphi 3 stuff that's missing from
Delphi 2.
110498 anme - Modified DoGetBitmap and DoGetDitherBitmap to
circumvent Delphi 2's braindead palette behaviour;
When realizing a palette the first and last 10 palette
entries are always set to the system palette colors no
matter what palette we attempt to define. This is
basically a Windows issue but since Delphi 3 doesn't
have this problem, I blame it on Delphi 2.
- Tweaked animation timing values to compensate for
the fact that we perform better than Mozilla.
Added FAST_AS_HELL conditional define to disable
tweaks.
- Added paint events to TGIFImage and TGIFPainter:
OnStartPaint, OnPaint, OnLoop and OnEndPaint.
- Changed TGIFPainter.ActiveImage to be a property.
- Added dummy component registration procedure Register
to allow design time GIF paint options to be set and
add design time support to Delphi 2.
The Register procedure by default disables the
goLoop option at design time to avoid using CPU
resources and distract the developer.
140498 anme - Fixed "TBitmap.PixelFormat := pf8bit" leak by using
method posted to borland.public.delphi.graphics by
Greg Chapman on 15 Feb 1998.
Scratch yet another bug that I simply couldn't locate.
Thank you to Yorai Aminov and Mark Zamoyta for
bringing the fix to my attention.
180498 anme - Misc changes after feedback from Reinier Sterkenburg:
* Added clear of image memory to
TGIFSubImage.Decompress to avoid "random noise" in
incomplete or corrupted images.
* Fixed bug in handling of Adobe Application
Extensions which caused "Abstract error".
- Added required compiler options.
- Fixed bug in TGIFImage.InternalPaint that caused a
"Out of system resources" error when width or height
of paint rect was <= 0 and multiple paint threads
where in use.
- Minor improvement of animation timing when running in
main thread.
- Removed PaintLock functions since they where not
nescessary and caused a major bottle neck when running
multiple threads on the same image.
This has caused a general performance improvement.
- Added conditional TPicture registration via the
REGISTER_TGIFIMAGE conditional define.
230498 anme - Fixed GetPixelFormat to support NT after feedback from
Reinier Sterkenburg.
- Added CopyPalette function to support old versions of
Delphi 2.x
- Added Exception trap to TGIFPainter.Execute.
Nescessary to make sure that an exception doesn't halt
the thread and thus hangs the application.
260598 anme - Implemented clipboard support.
- Source cleaned up for release.
260498 anme - Released as version 2.0
--------------------------------------------------------------------------------
Credits:
Many of the algorithms and methods used in this library are based on work
originally done by others:
The "TBitmap.PixelFormat := pf8bit" leak was fixed by:
* Greg Chapman <[email protected]>
with help from:
* Yorai Aminov <[email protected]> and
* Mark Zamoyta <[email protected]>
The Delphi 2.x port was based on work done by:
* Reinier Sterkenburg <[email protected]>
Reinier has also been *very* helpful with beta testing.
TransparentStretchBlt was fixed by:
* Brian Lowe of Acro Technology Inc. <[email protected]>
and brought to my attention by:
* Stefan Hoffmeister <[email protected]>
The dithering routines is based on work done by:
* David Ullrich <[email protected]>, who also helped me weed
out a few bugs in my implementation. Thanks.
* Jef Poskanzer in ppmquant.c from the netpbm library
The compressor is based on:
* ppmtogif.c (pbmplus) by Jef Poskanzer and others.
* gifcompr.c, gifencode.c (GIFENCOD) by David Rowley <[email protected]>.
* writegif.c (GIFTOOL) by David Koblas <[email protected]>
* compress.c - File compression ala IEEE Computer, June 1984, by
Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
Jim McKie (decvax!mcvax!jim)
Steve Davies (decvax!vax135!petsd!peora!srd)
Ken Turkowski (decvax!decwrl!turtlevax!ken)
James A. Woods (decvax!ihnp4!ames!jaw)
Joe Orost (decvax!vax135!petsd!joe)
* gcd.c (gd) by Tom Boutell <[email protected]>
The decompressor is based on work done by
* readgif.c (GIFTOOL) by David Koblas <[email protected]>
The hash routines was adapted from
* gif_hash.c (gif-lib) by Gershon Elber <[email protected]>
* with help from Filip Larsen <[email protected]>
Version 0.01 was based on work done by:
* Sean Wenzel, Compuserve 71736,1245
* Richard Dominelli, [email protected]
* Richard Shotbolt, Compuserve 100327,2305
* Stefan Böther, [email protected]
* Reinier Sterkenburg, [email protected]
--------------------------------------------------------------------------------
Known problems:
* Import of 16, 24 and 32 bit images (using the Assing method) will most
likely mess up the colors of the image.
Thanks to Mark Vaughan for pointing this out to me.
* Buffered display flickers when TGIFImage is used by a transparent TImage
component.
This is a problem with TImage caused by the fact that TImage was designed
with static images in mind. Not much I can do about it.
--------------------------------------------------------------------------------
To do (in rough order of priority):
* Palette optimizer with color quantization
* Non-compressed GIFs (LZW-less)
* Implement TGIFPainter support for:
Morphing
goValidateCanvas option
Source/Target canvas palette normalization
* Optimize TGIFSubImage.Decompress
* Implement TGIFPainter support for:
Interlaced display
Progressive display (piped load/decompress/display)
* Implement TGIFPainter support for:
UserInput
Text extension
********************************************************************************
*******************************************************************************)
interface
(*******************************************************************************
**
** Conditional Compiler Symbols
**
********************************************************************************
DEBUG Must be defined if any of the DEBUG_xxx
symbols are defined.
If the symbol is defined the source will not be
optimized and overflow- and range checks will be
enabled.
DEBUG_HASHPERFORMANCE Calculates hash table performance data.
DEBUG_HASHFILLFACTOR Calculates fill factor of hash table -
Interferes with DEBUG_HASHPERFORMANCE.
DEBUG_COMPRESSPERFORMANCE Calculates LZW compressor performance data.
DEBUG_DECOMPRESSPERFORMANCE Calculates LZW decompressor performance data.
GIF_NOSAFETY Define this symbol to disable overflow- and
range checks.
Ignore if the DEBUG symbol is defined.
STRICT_MOZILLA Define to mimic Mozilla as closely as possible.
If not defined, a slightly more "optimal"
implementation is used (IMHO).
FAST_AS_HELL Define this symbol to use strictly GIF compliant
(but too fast) animation timing.
Since our paint routines are much faster than
Mozilla's, the standard GIF and Mozilla values
causes animations to loop too fast.
If the symbol is _not_ defined, an alternative
set of tweaked timing values will be used.
The tweaked values are not optimal but are based
on tests performed on my reference system:
- Windows 95
- 133 MHz Pentium
- 64Mb RAM
- Diamond Stealth64/V3000
- 1600*1200 in 256 colors
The alternate values can be modified if you are
not satisfied with my defaults (they can be
found a few pages down).
REGISTER_TGIFIMAGE Define this symbol to register TGIFImage with
the TPicture class and integrate with TImage.
This is required to be able to display GIFs in
the TImage component (using TGIFImage anyway).
Undefine if you use another GIF library to
provide GIF support for TImage.
*)
{$DEFINE REGISTER_TGIFIMAGE}
{_$DEFINE DEBUG}
(*******************************************************************************
**
** Compiler Options required to compile this library
**
*******************************************************************************)
{$A+,B-,H+,J+,K-,M-,T-,X+}
{$IFDEF DEBUG}
{$C+} // ASSERTIONS
{$O-} // OPTIMIZATION
{$Q+} // OVERFLOWCHECKS
{$R+} // RANGECHECKS
{$ELSE}
{$C-} // ASSERTIONS
{$O+} // OPTIMIZATION
{$IFDEF GIF_NOSAFETY}
{$Q-}// OVERFLOWCHECKS
{$R-}// RANGECHECKS
{$ELSE}
{$Q+}// OVERFLOWCHECKS
{$R+}// RANGECHECKS
{$ENDIF}
{$ENDIF}
(*******************************************************************************
**
** External dependecies
**
*******************************************************************************)
uses
sysutils,
Windows,
Graphics,
Classes;
(*******************************************************************************
**
** Misc constants and support types
**
*******************************************************************************)
const
GIFMaxColors = 256; // Max number of colors supported by GIF
// Don't bother changing this value!
var
{$IFDEF FAST_AS_HELL}
GIFDelayExp: integer = 10; // Delay multiplier in mS.
{$ELSE}
GIFDelayExp: integer = 12; // Delay multiplier in mS. Tweaked.
{$ENDIF}
// * GIFDelayExp:
// The following delay values should all
// be multiplied by this value to
// calculate the effective time (in mS).
// According to the GIF specs, this
// value should be 10.
// Since our paint routines are much
// faster than Mozilla's, you might need
// to increase this value if your
// animations loops too fast. The
// optimal value is impossible to
// determine since it depends on the
// speed of the CPU, the viceo card,
// memory and many other factors.
GIFDefaultDelay: integer = 10; // * GIFDefaultDelay:
// Default animation delay.
// This value is used if no GCE is
// defined.
// (10 = 100 mS)
{$IFDEF FAST_AS_HELL}
GIFMinimumDelay: integer = 1; // Minimum delay (from Mozilla source).
// (1 = 10 mS)
{$ELSE}
GIFMinimumDelay: integer = 4; // Minimum delay (from Mozilla source).
// Tweaked.
{$ENDIF}
// * GIFMinimumDelay:
// The minumum delay used in the Mozilla
// source is 10mS. This corresponds to a
// value of 1. However, since our paint
// routines are much faster than
// Mozilla's, a value of 3 or 4 gives
// better results.
GIFMaximumDelay: integer = 1000; // * GIFMaximumDelay:
// Maximum delay when painter is running
// in main thread (goAsync is not set).
// This value guarantees that a very
// long and slow GIF does not hang the
// system.
// (1000 = 10000 mS = 10 Seconds)
type
TGIFVersion = (gvUnknown, gv87a, gv89a);
TGIFVersionRec = array[0..2] of char;
const
GIFVersions : array[gv87a..gv89a] of TGIFVersionRec = ('87a', '89a');
type
// TGIFImage only throws exceptions of type GIFException
GIFException = class(EInvalidGraphic);
// Severity level as indicated in the Warning methods and the OnWarning event
TGIFSeverity = (gsInfo, gsWarning, gsError);
(*******************************************************************************
**
** Delphi 2.x support
**
*******************************************************************************)
{$IFDEF VER90}
type
// TThreadList from Delphi 3 classes.pas
TThreadList = class
private
FList: TList;
FLock: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Add(Item: Pointer);
procedure Clear;
function LockList: TList;
procedure Remove(Item: Pointer);
procedure UnlockList;
end;
// From Delphi 3 sysutils.pas
EOutOfMemory = class(Exception);
// From Delphi 3 classes.pas
EOutOfResources = class(EOutOfMemory);
// From Delphi 3 windows.pas
PMaxLogPalette = ^TMaxLogPalette;
TMaxLogPalette = packed record
palVersion: Word;
palNumEntries: Word;
palPalEntry: array [Byte] of TPaletteEntry;
end; { TMaxLogPalette }
// From Delphi 3 graphics.pas. Used by the D3 TGraphic class.
TProgressStage = (psStarting, psRunning, psEnding);
TProgressEvent = procedure (Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string) of object;
{$ENDIF}
(*******************************************************************************
**
** Forward declarations
**
*******************************************************************************)
type
TGIFImage = class;
TGIFSubImage = class;
(*******************************************************************************
**
** TGIFItem
**
*******************************************************************************)
TGIFItem = class(TPersistent)
private
FGIFImage: TGIFImage;
protected
function GetVersion: TGIFVersion; virtual;
procedure Warning(Severity: TGIFSeverity; Message: string); virtual;
public
constructor Create(GIFImage: TGIFImage); virtual;
procedure SaveToStream(Stream: TStream); virtual; abstract;
procedure LoadFromStream(Stream: TStream); virtual; abstract;
property Version: TGIFVersion read GetVersion;
property Image: TGIFImage read FGIFImage;
end;
(*******************************************************************************
**
** TGIFList
**
*******************************************************************************)
TGIFList = class(TPersistent)
private
FItems: TList;
FImage: TGIFImage;
protected
function GetItem(Index: Integer): TGIFItem;
procedure SetItem(Index: Integer; Item: TGIFItem);
function GetCount: Integer;
procedure Warning(Severity: TGIFSeverity; Message: string); virtual;
public
constructor Create(Image: TGIFImage);
destructor Destroy; override;
function Add(Item: TGIFItem): Integer;
procedure Clear;
procedure Delete(Index: Integer);
procedure Exchange(Index1, Index2: Integer);
function First: TGIFItem;
function IndexOf(Item: TGIFItem): Integer;
procedure Insert(Index: Integer; Item: TGIFItem);
function Last: TGIFItem;
procedure Move(CurIndex, NewIndex: Integer);
function Remove(Item: TGIFItem): Integer;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream; Parent: TObject); virtual; abstract;
property Items[Index: Integer]: TGIFItem read GetItem write SetItem; default;
property Count: Integer read GetCount;
property List: TList read FItems;
property Image: TGIFImage read FImage;
end;
(*******************************************************************************
**
** TGIFColorMap
**
*******************************************************************************)
// One way to do it:
// TBaseColor = (bcRed, bcGreen, bcBlue);
// TGIFColor = array[bcRed..bcBlue] of BYTE;
// Another way:
TGIFColor = packed record
Red: byte;
Green: byte;
Blue: byte;
end;
TColorMap = packed array[0..GIFMaxColors-1] of TGIFColor;
PColorMap = ^TColorMap;
TGIFColorMap = class(TPersistent)
private
FColorMap : PColorMap;
FCount : integer;
FCapacity : integer;
FOptimized : boolean;
protected
function GetColor(Index: integer): TColor;
procedure SetColor(Index: integer; Value: TColor);
function GetBitsPerPixel: integer;
function DoOptimize(Image: TGIFSubImage; CleanUp: boolean): boolean;
procedure SetCapacity(Size: integer);
procedure Warning(Severity: TGIFSeverity; Message: string); virtual; abstract;
public
constructor Create;
destructor Destroy; override;
class function Color2RGB(Color: TColor): TGIFColor;
class function RGB2Color(Color: TGIFColor): TColor;
procedure SaveToStream(Stream: TStream);
procedure LoadFromStream(Stream: TStream; Count: integer);
procedure Assign(Source: TPersistent); override;
function IndexOf(Color: TColor): integer;
function Add(Color: TColor): integer;
procedure Delete(Index: integer);
procedure Clear;
function Optimize: boolean; virtual; abstract;
procedure Changed; virtual; abstract;
procedure ImportPalette(Palette: HPalette);
procedure ImportColorTable(Pal: pointer; Count: integer);
procedure ImportDIBColors(Handle: HDC);
function ExportPalette: HPalette;
property Colors[Index: integer]: TColor read GetColor write SetColor; default;
property Data: PColorMap read FColorMap;
property Count: integer read FCount;
property Optimized: boolean read FOptimized;
property BitsPerPixel: integer read GetBitsPerPixel;
end;
(*******************************************************************************
**
** TGIFHeader
**
*******************************************************************************)
TLogicalScreenDescriptor = packed record
ScreenWidth: word; { logical screen width }
ScreenHeight: word; { logical screen height }
PackedFields: byte; { packed fields }
BackgroundColorIndex: byte; { index to global color table }
AspectRatio: byte; { actual ratio = (AspectRatio + 15) / 64 }
end;
TGIFHeader = class(TGIFItem)
private
FLogicalScreenDescriptor: TLogicalScreenDescriptor;
FColorMap : TGIFColorMap;
procedure Prepare;
protected
function GetVersion: TGIFVersion; override;
function GetBackgroundColor: TColor;
procedure SetBackgroundColor(Color: TColor);
procedure SetBackgroundColorIndex(Index: BYTE);
function GetBitsPerPixel: integer;
function GetColorResolution: integer;
public
constructor Create(GIFImage: TGIFImage); override;
destructor Destroy; override;
procedure AssignTo(Dest: TPersistent); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
property Version: TGIFVersion read GetVersion;
property Width: WORD read FLogicalScreenDescriptor.ScreenWidth
write FLogicalScreenDescriptor.ScreenWidth;
property Height: WORD read FLogicalScreenDescriptor.ScreenHeight
write FLogicalScreenDescriptor.Screenheight;
property BackgroundColorIndex: BYTE read FLogicalScreenDescriptor.BackgroundColorIndex
write SetBackgroundColorIndex;
property BackgroundColor: TColor read GetBackgroundColor
write SetBackgroundColor;
property AspectRatio: BYTE read FLogicalScreenDescriptor.AspectRatio
write FLogicalScreenDescriptor.AspectRatio;
property ColorMap: TGIFColorMap read FColorMap;
property BitsPerPixel: integer read GetBitsPerPixel;
property ColorResolution: integer read GetColorResolution;
end;
(*******************************************************************************
**
** TGIFExtension
**
*******************************************************************************)
TGIFExtensionType = BYTE;
TGIFExtension = class;
TGIFExtensionClass = class of TGIFExtension;
TGIFGraphicControlExtension = class;
{$WARNINGS OFF} // To avoid warning about hiding base class constructor
TGIFExtension = class(TGIFItem)
private
FSubImage: TGIFSubImage;
protected
function GetExtensionType: TGIFExtensionType; virtual; abstract;
function GetVersion: TGIFVersion; override;
function DoReadFromStream(Stream: TStream): TGIFExtensionType;
class procedure RegisterExtension(elabel: BYTE; eClass: TGIFExtensionClass);
class function FindExtension(Stream: TStream): TGIFExtensionClass;
class function FindSubExtension(Stream: TStream): TGIFExtensionClass; virtual;
public
constructor Create(ASubImage: TGIFSubImage); virtual;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
property ExtensionType: TGIFExtensionType read GetExtensionType;
property SubImage: TGIFSubImage read FSubImage;
end;
{$WARNINGS ON}
(*******************************************************************************
**
** TGIFSubImage
**
*******************************************************************************)
TGIFExtensionList = class(TGIFList)
protected
function GetExtension(Index: Integer): TGIFExtension;
procedure SetExtension(Index: Integer; Extension: TGIFExtension);
public
procedure LoadFromStream(Stream: TStream; Parent: TObject); override;
property Extensions[Index: Integer]: TGIFExtension read GetExtension write SetExtension; default;
end;
TImageDescriptor = packed record
Separator: byte; { fixed value of ImageSeparator }
Left: word; { Column in pixels in respect to left edge of logical screen }
Top: word; { row in pixels in respect to top of logical screen }
Width: word; { width of image in pixels }
Height: word; { height of image in pixels }
PackedFields: byte; { Bit fields }
end;
TGIFSubImage = class(TGIFItem)
private
FDIBInfo : PBitmapInfo;
FDIBBits : pointer;
FDIBInfoSize : integer;
FDIBBitsSize : longInt;
FBitmap : TBitmap;
FMask : HBitmap;
FNeedMask : boolean;
FLocalPalette : HPalette;
FData : PChar;
FDataSize : integer;
FColorMap : TGIFColorMap;
FImageDescriptor : TImageDescriptor;
FExtensions : TGIFExtensionList;
FTransparent : boolean;
FGCE : TGIFGraphicControlExtension;
procedure Prepare;
procedure Compress(Stream: TStream);
procedure Decompress(Stream: TStream);
protected
function GetVersion: TGIFVersion; override;
function GetInterlaced: boolean;
procedure SetInterlaced(Value: boolean);
function GetColorResolution: integer;
function GetBitsPerPixel: integer;
procedure AssignTo(Dest: TPersistent); override;
function DoGetBitmap: TBitmap;
function DoGetDitherBitmap: TBitmap;
function GetBitmap: TBitmap;
procedure SetBitmap(Value: TBitmap);
procedure FreeBitmap;
procedure FreeMask;
function GetEmpty: Boolean;
function GetPalette: HPALETTE;
procedure SetPalette(Value: HPalette);
function GetActiveColorMap: TGIFColorMap;
function GetBoundsRect: TRect;
function GetClientRect: TRect;
function GetPixel(x, y: integer): BYTE;
procedure NewBitmap;
procedure NewImage;
procedure FreeDIB;
procedure BitmapToDIB(ABitmap: TBitmap);
procedure DIBToBitmap(ABitmap: TBitmap);
function GetScanLine(Row: Integer): PChar;
function ScaleRect(DestRect: TRect): TRect;
function HasMask: boolean;
function GetBounds(Index: integer): WORD;
procedure SetBounds(Index: integer; Value: WORD);
public
constructor Create(GIFImage: TGIFImage); override;
destructor Destroy; override;
procedure Clear;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
procedure LoadFromFile(const Filename: string); virtual;
procedure Assign(Source: TPersistent); override;
procedure Draw(ACanvas: TCanvas; const Rect: TRect; DoTransparent: boolean);
procedure StretchDraw(ACanvas: TCanvas; const Rect: TRect; DoTransparent: boolean);
property Left: WORD index 1 read GetBounds write SetBounds;
property Top: WORD index 2 read GetBounds write SetBounds;
property Width: WORD index 3 read GetBounds write SetBounds;
property Height: WORD index 4 read GetBounds write SetBounds;
property BoundsRect: TRect read GetBoundsRect;
property ClientRect: TRect read GetClientRect;
property Interlaced: boolean read GetInterlaced write SetInterlaced;
property ColorMap: TGIFColorMap read FColorMap;
property ActiveColorMap: TGIFColorMap read GetActiveColorMap;
property Data: PChar read FData;
property DataSize: integer read FDataSize;
property Extensions: TGIFExtensionList read FExtensions;
property Version: TGIFVersion read GetVersion;
property ColorResolution: integer read GetColorResolution;
property BitsPerPixel: integer read GetBitsPerPixel;
property Bitmap: TBitmap read GetBitmap write SetBitmap;
property Mask: HBitmap read FMask;
property Palette: HPALETTE read GetPalette write SetPalette;
property Empty: boolean read GetEmpty;
property Transparent: boolean read FTransparent;
property GraphicControlExtension: TGIFGraphicControlExtension read FGCE;
property Pixels[x, y: integer]: BYTE read GetPixel;
end;
(*******************************************************************************
**
** TGIFTrailer
**
*******************************************************************************)
TGIFTrailer = class(TGIFItem)
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
end;
(*******************************************************************************
**
** TGIFGraphicControlExtension
**
*******************************************************************************)
// Graphic Control Extension block a.k.a GCE
TGIFGCERec = packed record
BlockSize: byte; { should be 4 }
PackedFields: Byte;
DelayTime: Word; { in centiseconds }
TransparentColorIndex: Byte;
Terminator: Byte;
end;
TDisposalMethod = (dmNone, dmNoDisposal, dmBackground, dmPrevious);
TGIFGraphicControlExtension = class(TGIFExtension)
private
FGCExtension: TGIFGCERec;
protected
function GetExtensionType: TGIFExtensionType; override;
function GetTransparent: boolean;