-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathImagingNetworkGraphics.pas
2699 lines (2458 loc) · 86 KB
/
ImagingNetworkGraphics.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
{
Vampyre Imaging Library
by Marek Mauder
https://github.com/galfar/imaginglib
https://imaginglib.sourceforge.io
- - - - -
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0.
}
{ This unit contains image format loaders/savers for Network Graphics image
file formats PNG, MNG, and JNG.}
unit ImagingNetworkGraphics;
interface
{$I ImagingOptions.inc}
{ If MNG support is enabled we must make sure PNG and JNG are enabled too.}
{$IFNDEF DONT_LINK_MNG}
{$UNDEF DONT_LINK_PNG}
{$UNDEF DONT_LINK_JNG}
{$ENDIF}
uses
Types, SysUtils, Classes, ImagingTypes, Imaging, ImagingUtility, ImagingFormats, dzlib;
type
{ Basic class for Network Graphics file formats loaders/savers.}
TNetworkGraphicsFileFormat = class(TImageFileFormat)
protected
FSignature: TChar8;
FPreFilter: LongInt;
FCompressLevel: LongInt;
FLossyCompression: LongBool;
FLossyAlpha: LongBool;
FQuality: LongInt;
FProgressive: LongBool;
FZLibStrategy: Integer;
function GetSupportedFormats: TImageFormats; override;
procedure ConvertToSupported(var Image: TImageData;
const Info: TImageFormatInfo); override;
procedure Define; override;
public
function TestFormat(Handle: TImagingHandle): Boolean; override;
procedure CheckOptionsValidity; override;
published
{ Sets precompression filter used when saving images with lossless compression.
Allowed values are: 0 (none), 1 (sub), 2 (up), 3 (average), 4 (paeth),
5 (use 0 for indexed/gray images and 4 for RGB/ARGB images),
6 (adaptive filtering - use best filter for each scanline - very slow).
Note that filters 3 and 4 are much slower than filters 1 and 2.
Default value is 5.}
property PreFilter: LongInt read FPreFilter write FPreFilter;
{ Sets ZLib compression level used when saving images with lossless compression.
Allowed values are in range 0 (no compression) to 9 (best compression).
Default value is 5.}
property CompressLevel: LongInt read FCompressLevel write FCompressLevel;
{ Specifies whether MNG animation frames are saved with lossy or lossless
compression. Lossless frames are saved as PNG images and lossy frames are
saved as JNG images. Allowed values are 0 (False) and 1 (True).
Default value is 0.}
property LossyCompression: LongBool read FLossyCompression write FLossyCompression;
{ Defines whether alpha channel of lossy MNG frames or JNG images
is lossy compressed too. Allowed values are 0 (False) and 1 (True).
Default value is 0.}
property LossyAlpha: LongBool read FLossyAlpha write FLossyAlpha;
{ Specifies compression quality used when saving lossy MNG frames or JNG images.
For details look at ImagingJpegQuality option.}
property Quality: LongInt read FQuality write FQuality;
{ Specifies whether images are saved in progressive format when saving lossy
MNG frames or JNG images. For details look at ImagingJpegProgressive.}
property Progressive: LongBool read FProgressive write FProgressive;
end;
{ Class for loading Portable Network Graphics Images.
Loads all types of this image format (all images in png test suite)
and saves all types with bitcount >= 8 (non-interlaced only).
Compression level and filtering can be set by options interface.
Supported ancillary chunks (loading):
tRNS, bKGD
(for indexed images transparency contains alpha values for palette,
RGB/Gray images with transparency are converted to formats with alpha
and pixels with transparent color are replaced with background color
with alpha = 0).}
TPNGFileFormat = class(TNetworkGraphicsFileFormat)
private
FLoadAnimated: LongBool;
protected
procedure Define; override;
function LoadData(Handle: TImagingHandle; var Images: TDynImageDataArray;
OnlyFirstLevel: Boolean): Boolean; override;
function SaveData(Handle: TImagingHandle; const Images: TDynImageDataArray;
Index: LongInt): Boolean; override;
published
property LoadAnimated: LongBool read FLoadAnimated write FLoadAnimated;
end;
{$IFNDEF DONT_LINK_MNG}
{ Class for loading Multiple Network Graphics files.
This format has complex animation capabilities but Imaging only
extracts frames. Individual frames are stored as standard PNG or JNG
images. Loads all types of these frames stored in IHDR-IEND and
JHDR-IEND streams (Note that there are MNG chunks
like BASI which define images but does not contain image data itself,
those are ignored).
Imaging saves MNG files as MNG-VLC (very low complexity) so it is basically
an array of image frames without MNG animation chunks. Frames can be saved
as lossless PNG or lossy JNG images (look at TPNGFileFormat and
TJNGFileFormat for info). Every frame can be in different data format.
Many frame compression settings can be modified by options interface.}
TMNGFileFormat = class(TNetworkGraphicsFileFormat)
protected
procedure Define; override;
function LoadData(Handle: TImagingHandle; var Images: TDynImageDataArray;
OnlyFirstLevel: Boolean): Boolean; override;
function SaveData(Handle: TImagingHandle; const Images: TDynImageDataArray;
Index: LongInt): Boolean; override;
end;
{$ENDIF}
{$IFNDEF DONT_LINK_JNG}
{ Class for loading JPEG Network Graphics Images.
Loads all types of this image format (all images in jng test suite)
and saves all types except 12 bit JPEGs.
Alpha channel in JNG images is stored separately from color/gray data and
can be lossy (as JPEG image) or lossless (as PNG image) compressed.
Type of alpha compression, compression level and quality,
and filtering can be set by options interface.
Supported ancillary chunks (loading):
tRNS, bKGD
(Images with transparency are converted to formats with alpha
and pixels with transparent color are replaced with background color
with alpha = 0).}
TJNGFileFormat = class(TNetworkGraphicsFileFormat)
protected
procedure Define; override;
function LoadData(Handle: TImagingHandle; var Images: TDynImageDataArray;
OnlyFirstLevel: Boolean): Boolean; override;
function SaveData(Handle: TImagingHandle; const Images: TDynImageDataArray;
Index: LongInt): Boolean; override;
end;
{$ENDIF}
implementation
uses
{$IFNDEF DONT_LINK_JNG}
ImagingJpeg, ImagingIO,
{$ENDIF}
ImagingCanvases;
const
NGDefaultPreFilter = 5;
NGDefaultCompressLevel = 5;
NGDefaultLossyAlpha = False;
NGDefaultLossyCompression = False;
NGDefaultProgressive = False;
NGDefaultQuality = 90;
NGLosslessFormats: TImageFormats = [ifIndex8, ifGray8, ifA8Gray8, ifGray16,
ifA16Gray16, ifR8G8B8, ifA8R8G8B8, ifR16G16B16, ifA16R16G16B16, ifB16G16R16,
ifA16B16G16R16, ifBinary];
NGLossyFormats: TImageFormats = [ifGray8, ifA8Gray8, ifR8G8B8, ifA8R8G8B8];
PNGDefaultLoadAnimated = True;
NGDefaultZLibStrategy = 1; // Z_FILTERED
SPNGFormatName = 'Portable Network Graphics';
SPNGMasks = '*.png';
SMNGFormatName = 'Multiple Network Graphics';
SMNGMasks = '*.mng';
SJNGFormatName = 'JPEG Network Graphics';
SJNGMasks = '*.jng';
resourcestring
SErrorLoadingChunk = 'Error when reading %s chunk data. File may be corrupted.';
type
{ Chunk header.}
TChunkHeader = packed record
DataSize: UInt32;
ChunkID: TChar4;
end;
{ IHDR chunk format - PNG header.}
TIHDR = packed record
Width: UInt32; // Image width
Height: UInt32; // Image height
BitDepth: Byte; // Bits per pixel or bits per sample (for truecolor)
ColorType: Byte; // 0 = grayscale, 2 = truecolor, 3 = palette,
// 4 = gray + alpha, 6 = truecolor + alpha
Compression: Byte; // Compression type: 0 = ZLib
Filter: Byte; // Used precompress filter
Interlacing: Byte; // Used interlacing: 0 = no int, 1 = Adam7
end;
PIHDR = ^TIHDR;
{ MHDR chunk format - MNG header.}
TMHDR = packed record
FrameWidth: UInt32; // Frame width
FrameHeight: UInt32; // Frame height
TicksPerSecond: UInt32; // FPS of animation
NominalLayerCount: UInt32; // Number of layers in file
NominalFrameCount: UInt32; // Number of frames in file
NominalPlayTime: UInt32; // Play time of animation in ticks
SimplicityProfile: UInt32; // Defines which MNG features are used in this file
end;
PMHDR = ^TMHDR;
{ JHDR chunk format - JNG header.}
TJHDR = packed record
Width: UInt32; // Image width
Height: UInt32; // Image height
ColorType: Byte; // 8 = grayscale (Y), 10 = color (YCbCr),
// 12 = gray + alpha (Y-alpha), 14 = color + alpha (YCbCr-alpha)
SampleDepth: Byte; // 8, 12 or 20 (8 and 12 samples together) bit
Compression: Byte; // Compression type: 8 = Huffman coding
Interlacing: Byte; // 0 = single scan, 8 = progressive
AlphaSampleDepth: Byte; // 0, 1, 2, 4, 8, 16 if alpha compression is 0 (PNG)
// 8 if alpha compression is 8 (JNG)
AlphaCompression: Byte; // 0 = PNG grayscale IDAT, 8 = grayscale 8-bit JPEG
AlphaFilter: Byte; // 0 = PNG filter or no filter (JPEG)
AlphaInterlacing: Byte; // 0 = non interlaced
end;
PJHDR = ^TJHDR;
{ acTL chunk format - APNG animation control.}
TacTL = packed record
NumFrames: UInt32; // Number of frames
NumPlay: UInt32; // Number of times to loop the animation (0 = inf)
end;
PacTL =^TacTL;
{ fcTL chunk format - APNG frame control.}
TfcTL = packed record
SeqNumber: UInt32; // Sequence number of the animation chunk, starting from 0
Width: UInt32; // Width of the following frame
Height: UInt32; // Height of the following frame
XOffset: UInt32; // X position at which to render the following frame
YOffset: UInt32; // Y position at which to render the following frame
DelayNumer: Word; // Frame delay fraction numerator
DelayDenom: Word; // Frame delay fraction denominator
DisposeOp: Byte; // Type of frame area disposal to be done after rendering this frame
BlendOp: Byte; // Type of frame area rendering for this frame
end;
PfcTL = ^TfcTL;
{ pHYs chunk format - encodes the absolute or relative dimensions of pixels.}
TpHYs = packed record
PixelsPerUnitX: UInt32;
PixelsPerUnitY: UInt32;
UnitSpecifier: Byte;
end;
PpHYs = ^TpHYs;
const
{ PNG file identifier.}
PNGSignature: TChar8 = #$89'PNG'#$0D#$0A#$1A#$0A;
{ MNG file identifier.}
MNGSignature: TChar8 = #$8A'MNG'#$0D#$0A#$1A#$0A;
{ JNG file identifier.}
JNGSignature: TChar8 = #$8B'JNG'#$0D#$0A#$1A#$0A;
{ Constants for chunk identifiers and signature identifiers.
They are in big-endian format.}
IHDRChunk: TChar4 = 'IHDR';
IENDChunk: TChar4 = 'IEND';
MHDRChunk: TChar4 = 'MHDR';
MENDChunk: TChar4 = 'MEND';
JHDRChunk: TChar4 = 'JHDR';
IDATChunk: TChar4 = 'IDAT';
JDATChunk: TChar4 = 'JDAT';
JDAAChunk: TChar4 = 'JDAA';
JSEPChunk: TChar4 = 'JSEP';
PLTEChunk: TChar4 = 'PLTE';
BACKChunk: TChar4 = 'BACK';
DEFIChunk: TChar4 = 'DEFI';
TERMChunk: TChar4 = 'TERM';
tRNSChunk: TChar4 = 'tRNS';
bKGDChunk: TChar4 = 'bKGD';
gAMAChunk: TChar4 = 'gAMA';
acTLChunk: TChar4 = 'acTL';
fcTLChunk: TChar4 = 'fcTL';
fdATChunk: TChar4 = 'fdAT';
pHYsChunk: TChar4 = 'pHYs';
{ APNG frame dispose operations.}
DisposeOpNone = 0;
DisposeOpBackground = 1;
DisposeOpPrevious = 2;
{ APNG frame blending modes}
BlendOpSource = 0;
BlendOpOver = 1;
{ Interlace start and offsets.}
RowStart: array[0..6] of LongInt = (0, 0, 4, 0, 2, 0, 1);
ColumnStart: array[0..6] of LongInt = (0, 4, 0, 2, 0, 1, 0);
RowIncrement: array[0..6] of LongInt = (8, 8, 8, 4, 4, 2, 2);
ColumnIncrement: array[0..6] of LongInt = (8, 8, 4, 4, 2, 2, 1);
type
{ Helper class that holds information about MNG frame in PNG or JNG format.}
TFrameInfo = class
public
Index: Integer;
FrameWidth, FrameHeight: LongInt;
IsJpegFrame: Boolean;
IHDR: TIHDR;
JHDR: TJHDR;
fcTL: TfcTL;
pHYs: TpHYs;
Palette: PPalette24;
PaletteEntries: LongInt;
Transparency: Pointer;
TransparencySize: LongInt;
Background: Pointer;
BackgroundSize: LongInt;
IDATMemory: TMemoryStream;
JDATMemory: TMemoryStream;
JDAAMemory: TMemoryStream;
constructor Create(AIndex: Integer);
destructor Destroy; override;
procedure AssignSharedProps(Source: TFrameInfo);
end;
{ Defines type of Network Graphics file.}
TNGFileType = (ngPNG, ngAPNG, ngMNG, ngJNG);
TNGFileHandler = class
public
FileFormat: TNetworkGraphicsFileFormat;
FileType: TNGFileType;
Frames: array of TFrameInfo;
MHDR: TMHDR; // Main header for MNG files
acTL: TacTL; // Global anim control for APNG files
GlobalPalette: PPalette24;
GlobalPaletteEntries: LongInt;
GlobalTransparency: Pointer;
GlobalTransparencySize: LongInt;
constructor Create(AFileFormat: TNetworkGraphicsFileFormat);
destructor Destroy; override;
procedure Clear;
function GetLastFrame: TFrameInfo;
function AddFrameInfo: TFrameInfo;
procedure LoadMetaData;
end;
{ Network Graphics file parser and frame converter.}
TNGFileLoader = class(TNGFileHandler)
public
function LoadFile(Handle: TImagingHandle): Boolean;
procedure LoadImageFromPNGFrame(FrameWidth, FrameHeight: LongInt; const IHDR: TIHDR; IDATStream: TMemoryStream; var Image: TImageData);
{$IFNDEF DONT_LINK_JNG}
procedure LoadImageFromJNGFrame(FrameWidth, FrameHeight: LongInt; const JHDR: TJHDR; IDATStream, JDATStream, JDAAStream: TMemoryStream; var Image: TImageData);
{$ENDIF}
procedure ApplyFrameSettings(Frame: TFrameInfo; var Image: TImageData);
end;
TNGFileSaver = class(TNGFileHandler)
public
PreFilter: LongInt;
CompressLevel: LongInt;
LossyAlpha: Boolean;
Quality: LongInt;
Progressive: Boolean;
ZLibStrategy: Integer;
function SaveFile(Handle: TImagingHandle): Boolean;
procedure AddFrame(const Image: TImageData; IsJpegFrame: Boolean);
procedure StoreImageToPNGFrame(const IHDR: TIHDR; Bits: Pointer; FmtInfo: TImageFormatInfo; IDATStream: TMemoryStream);
{$IFNDEF DONT_LINK_JNG}
procedure StoreImageToJNGFrame(const JHDR: TJHDR; const Image: TImageData; IDATStream, JDATStream, JDAAStream: TMemoryStream);
{$ENDIF}
procedure SetFileOptions;
end;
{$IFNDEF DONT_LINK_JNG}
TCustomIOJpegFileFormat = class(TJpegFileFormat)
protected
FCustomIO: TIOFunctions;
procedure SetJpegIO(const JpegIO: TIOFunctions); override;
procedure SetCustomIO(const CustomIO: TIOFunctions);
end;
{$ENDIF}
TAPNGAnimator = class
public
class procedure Animate(var Images: TDynImageDataArray; const acTL: TacTL; const SrcFrames: array of TFrameInfo);
end;
{ Helper routines }
function PaethPredictor(A, B, C: LongInt): LongInt; {$IFDEF USE_INLINE}inline;{$ENDIF}
var
P, PA, PB, PC: LongInt;
begin
P := A + B - C;
PA := Abs(P - A);
PB := Abs(P - B);
PC := Abs(P - C);
if (PA <= PB) and (PA <= PC) then
Result := A
else
if PB <= PC then
Result := B
else
Result := C;
end;
procedure SwapRGB(Line: PByte; Width, SampleDepth, BytesPerPixel: LongInt);
var
I: LongInt;
Tmp: Word;
begin
case SampleDepth of
8:
for I := 0 to Width - 1 do
with PColor24Rec(Line)^ do
begin
Tmp := R;
R := B;
B := Tmp;
Inc(Line, BytesPerPixel);
end;
16:
for I := 0 to Width - 1 do
with PColor48Rec(Line)^ do
begin
Tmp := R;
R := B;
B := Tmp;
Inc(Line, BytesPerPixel);
end;
end;
end;
{$IFNDEF DONT_LINK_JNG}
{ TCustomIOJpegFileFormat class implementation }
procedure TCustomIOJpegFileFormat.SetCustomIO(const CustomIO: TIOFunctions);
begin
FCustomIO := CustomIO;
end;
procedure TCustomIOJpegFileFormat.SetJpegIO(const JpegIO: TIOFunctions);
begin
inherited SetJpegIO(FCustomIO);
end;
{$ENDIF}
{ TFrameInfo class implementation }
constructor TFrameInfo.Create(AIndex: Integer);
begin
Index := AIndex;
IDATMemory := TMemoryStream.Create;
JDATMemory := TMemoryStream.Create;
JDAAMemory := TMemoryStream.Create;
end;
destructor TFrameInfo.Destroy;
begin
FreeMem(Palette);
FreeMem(Transparency);
FreeMem(Background);
IDATMemory.Free;
JDATMemory.Free;
JDAAMemory.Free;
inherited Destroy;
end;
procedure TFrameInfo.AssignSharedProps(Source: TFrameInfo);
begin
IHDR := Source.IHDR;
JHDR := Source.JHDR;
PaletteEntries := Source.PaletteEntries;
GetMem(Palette, PaletteEntries * SizeOf(TColor24Rec));
Move(Source.Palette^, Palette^, PaletteEntries * SizeOf(TColor24Rec));
TransparencySize := Source.TransparencySize;
GetMem(Transparency, TransparencySize);
Move(Source.Transparency^, Transparency^, TransparencySize);
end;
{ TNGFileHandler class implementation}
destructor TNGFileHandler.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TNGFileHandler.Clear;
var
I: LongInt;
begin
for I := 0 to Length(Frames) - 1 do
Frames[I].Free;
SetLength(Frames, 0);
FreeMemNil(GlobalPalette);
GlobalPaletteEntries := 0;
FreeMemNil(GlobalTransparency);
GlobalTransparencySize := 0;
end;
constructor TNGFileHandler.Create(AFileFormat: TNetworkGraphicsFileFormat);
begin
FileFormat := AFileFormat;
end;
function TNGFileHandler.GetLastFrame: TFrameInfo;
var
Len: LongInt;
begin
Len := Length(Frames);
if Len > 0 then
Result := Frames[Len - 1]
else
Result := nil;
end;
procedure TNGFileHandler.LoadMetaData;
var
I: Integer;
Delay, Denom: Integer;
begin
if FileType = ngAPNG then
begin
// Num plays of APNG animation
FileFormat.FMetadata.SetMetaItem(SMetaAnimationLoops, acTL.NumPlay);
end;
for I := 0 to High(Frames) do
begin
if Frames[I].pHYs.UnitSpecifier = 1 then
begin
// Store physical pixel dimensions, in PNG stored as pixels per meter DPM
FileFormat.FMetadata.SetPhysicalPixelSize(ruDpm, Frames[I].pHYs.PixelsPerUnitX,
Frames[I].pHYs.PixelsPerUnitY);
end;
if FileType = ngAPNG then
begin
// Store frame delay of APNG file frame
Denom := Frames[I].fcTL.DelayDenom;
if Denom = 0 then
Denom := 100;
Delay := Round(1000 * (Frames[I].fcTL.DelayNumer / Denom));
FileFormat.FMetadata.SetMetaItem(SMetaFrameDelay, Delay, I);
end;
end;
end;
function TNGFileHandler.AddFrameInfo: TFrameInfo;
var
Len: LongInt;
begin
Len := Length(Frames);
SetLength(Frames, Len + 1);
Result := TFrameInfo.Create(Len);
Frames[Len] := Result;
end;
{ TNGFileLoader class implementation}
function TNGFileLoader.LoadFile(Handle: TImagingHandle): Boolean;
var
Sig: TChar8;
Chunk: TChunkHeader;
ChunkData: Pointer;
ChunkCrc: UInt32;
procedure ReadChunk;
begin
GetIO.Read(Handle, @Chunk, SizeOf(Chunk));
Chunk.DataSize := SwapEndianUInt32(Chunk.DataSize);
end;
procedure ReadChunkData;
var
ReadBytes: UInt32;
begin
FreeMemNil(ChunkData);
GetMem(ChunkData, Chunk.DataSize);
ReadBytes := GetIO.Read(Handle, ChunkData, Chunk.DataSize);
GetIO.Read(Handle, @ChunkCrc, SizeOf(ChunkCrc));
if ReadBytes <> Chunk.DataSize then
RaiseImaging(SErrorLoadingChunk, [string(Chunk.ChunkID)]);
end;
procedure SkipChunkData;
begin
GetIO.Seek(Handle, Chunk.DataSize + SizeOf(ChunkCrc), smFromCurrent);
end;
procedure StartNewPNGImage;
var
Frame: TFrameInfo;
begin
ReadChunkData;
if Chunk.ChunkID = fcTLChunk then
begin
if (Length(Frames) = 1) and (Frames[0].IDATMemory.Size = 0) then
begin
// First fcTL chunk maybe for first IDAT frame which is alredy created
Frame := Frames[0];
end
else
begin
// Subsequent APNG frames with data in fdAT
Frame := AddFrameInfo;
// Copy some shared props from first frame (IHDR is the same for all APNG frames, palette etc)
Frame.AssignSharedProps(Frames[0]);
end;
Frame.fcTL := PfcTL(ChunkData)^;
SwapEndianUInt32(@Frame.fcTL, 5);
Frame.fcTL.DelayNumer := SwapEndianWord(Frame.fcTL.DelayNumer);
Frame.fcTL.DelayDenom := SwapEndianWord(Frame.fcTL.DelayDenom);
Frame.FrameWidth := Frame.fcTL.Width;
Frame.FrameHeight := Frame.fcTL.Height;
end
else
begin
// This is frame defined by IHDR chunk
Frame := AddFrameInfo;
Frame.IHDR := PIHDR(ChunkData)^;
SwapEndianUInt32(@Frame.IHDR, 2);
Frame.FrameWidth := Frame.IHDR.Width;
Frame.FrameHeight := Frame.IHDR.Height;
end;
Frame.IsJpegFrame := False;
end;
procedure StartNewJNGImage;
var
Frame: TFrameInfo;
begin
ReadChunkData;
Frame := AddFrameInfo;
Frame.IsJpegFrame := True;
Frame.JHDR := PJHDR(ChunkData)^;
SwapEndianUInt32(@Frame.JHDR, 2);
Frame.FrameWidth := Frame.JHDR.Width;
Frame.FrameHeight := Frame.JHDR.Height;
end;
procedure AppendIDAT;
begin
ReadChunkData;
// Append current IDAT/fdAT chunk to storage stream
if Chunk.ChunkID = IDATChunk then
GetLastFrame.IDATMemory.Write(ChunkData^, Chunk.DataSize)
else if Chunk.ChunkID = fdATChunk then
GetLastFrame.IDATMemory.Write(PByteArray(ChunkData)[4], Chunk.DataSize - SizeOf(UInt32));
end;
procedure AppendJDAT;
begin
ReadChunkData;
// Append current JDAT chunk to storage stream
GetLastFrame.JDATMemory.Write(ChunkData^, Chunk.DataSize);
end;
procedure AppendJDAA;
begin
ReadChunkData;
// Append current JDAA chunk to storage stream
GetLastFrame.JDAAMemory.Write(ChunkData^, Chunk.DataSize);
end;
procedure LoadPLTE;
begin
ReadChunkData;
if GetLastFrame = nil then
begin
// Load global palette
GetMem(GlobalPalette, Chunk.DataSize);
Move(ChunkData^, GlobalPalette^, Chunk.DataSize);
GlobalPaletteEntries := Chunk.DataSize div 3;
end
else if GetLastFrame.Palette = nil then
begin
if (Chunk.DataSize = 0) and (GlobalPalette <> nil) then
begin
// Use global palette
GetMem(GetLastFrame.Palette, GlobalPaletteEntries * SizeOf(TColor24Rec));
Move(GlobalPalette^, GetLastFrame.Palette^, GlobalPaletteEntries * SizeOf(TColor24Rec));
GetLastFrame.PaletteEntries := GlobalPaletteEntries;
end
else
begin
// Load pal from PLTE chunk
GetMem(GetLastFrame.Palette, Chunk.DataSize);
Move(ChunkData^, GetLastFrame.Palette^, Chunk.DataSize);
GetLastFrame.PaletteEntries := Chunk.DataSize div 3;
end;
end;
end;
procedure LoadtRNS;
begin
ReadChunkData;
if GetLastFrame = nil then
begin
// Load global transparency
GetMem(GlobalTransparency, Chunk.DataSize);
Move(ChunkData^, GlobalTransparency^, Chunk.DataSize);
GlobalTransparencySize := Chunk.DataSize;
end
else if GetLastFrame.Transparency = nil then
begin
if (Chunk.DataSize = 0) and (GlobalTransparency <> nil) then
begin
// Use global transparency
GetMem(GetLastFrame.Transparency, GlobalTransparencySize);
Move(GlobalTransparency^, GetLastFrame.Transparency^, Chunk.DataSize);
GetLastFrame.TransparencySize := GlobalTransparencySize;
end
else
begin
// Load pal from tRNS chunk
GetMem(GetLastFrame.Transparency, Chunk.DataSize);
Move(ChunkData^, GetLastFrame.Transparency^, Chunk.DataSize);
GetLastFrame.TransparencySize := Chunk.DataSize;
end;
end;
end;
procedure LoadbKGD;
begin
ReadChunkData;
if GetLastFrame.Background = nil then
begin
GetMem(GetLastFrame.Background, Chunk.DataSize);
Move(ChunkData^, GetLastFrame.Background^, Chunk.DataSize);
GetLastFrame.BackgroundSize := Chunk.DataSize;
end;
end;
procedure HandleacTL;
begin
FileType := ngAPNG;
ReadChunkData;
acTL := PacTL(ChunkData)^;
SwapEndianUInt32(@acTL, SizeOf(acTL) div SizeOf(UInt32));
end;
procedure LoadpHYs;
begin
ReadChunkData;
with GetLastFrame do
begin
pHYs := PpHYs(ChunkData)^;
SwapEndianUInt32(@pHYs, SizeOf(pHYs) div SizeOf(UInt32));
end;
end;
begin
Result := False;
Clear;
ChunkData := nil;
with GetIO do
try
Read(Handle, @Sig, SizeOf(Sig));
// Set file type according to the signature
if Sig = PNGSignature then FileType := ngPNG
else if Sig = MNGSignature then FileType := ngMNG
else if Sig = JNGSignature then FileType := ngJNG
else Exit;
if FileType = ngMNG then
begin
// Store MNG header if present
ReadChunk;
ReadChunkData;
MHDR := PMHDR(ChunkData)^;
SwapEndianUInt32(@MHDR, SizeOf(MHDR) div SizeOf(UInt32));
end;
// Read chunks until ending chunk or EOF is reached
repeat
ReadChunk;
if (Chunk.ChunkID = IHDRChunk) or (Chunk.ChunkID = fcTLChunk) then StartNewPNGImage
else if Chunk.ChunkID = JHDRChunk then StartNewJNGImage
else if (Chunk.ChunkID = IDATChunk) or (Chunk.ChunkID = fdATChunk) then AppendIDAT
else if Chunk.ChunkID = JDATChunk then AppendJDAT
else if Chunk.ChunkID = JDAAChunk then AppendJDAA
else if Chunk.ChunkID = PLTEChunk then LoadPLTE
else if Chunk.ChunkID = tRNSChunk then LoadtRNS
else if Chunk.ChunkID = bKGDChunk then LoadbKGD
else if Chunk.ChunkID = acTLChunk then HandleacTL
else if Chunk.ChunkID = pHYsChunk then LoadpHYs
else SkipChunkData;
until Eof(Handle) or (Chunk.ChunkID = MENDChunk) or
((FileType <> ngMNG) and (Chunk.ChunkID = IENDChunk));
Result := True;
finally
FreeMemNil(ChunkData);
end;
end;
procedure TNGFileLoader.LoadImageFromPNGFrame(FrameWidth, FrameHeight: LongInt; const IHDR: TIHDR;
IDATStream: TMemoryStream; var Image: TImageData);
type
TGetPixelFunc = function(Line: PByteArray; X: LongInt): Byte;
var
LineBuffer: array[Boolean] of PByteArray;
ActLine: Boolean;
Data, TotalBuffer, ZeroLine, PrevLine: Pointer;
BitCount, TotalPos, BytesPerPixel, I, Pass,
SrcDataSize, BytesPerLine, InterlaceLineBytes, InterlaceWidth: LongInt;
TotalSize: Integer;
Info: TImageFormatInfo;
procedure DecodeAdam7;
const
BitTable: array[1..8] of LongInt = ($1, $3, 0, $F, 0, 0, 0, $FF);
StartBit: array[1..8] of LongInt = (7, 6, 0, 4, 0, 0, 0, 0);
var
Src, Dst, Dst2: PByte;
CurBit, Col: LongInt;
begin
Src := @LineBuffer[ActLine][1];
Col := ColumnStart[Pass];
with Image do
case BitCount of
1, 2, 4:
begin
Dst := @PByteArray(Data)[I * BytesPerLine];
repeat
CurBit := StartBit[BitCount];
repeat
Dst2 := @PByteArray(Dst)[(BitCount * Col) shr 3];
Dst2^ := Dst2^ or ((Src^ shr CurBit) and BitTable[BitCount])
shl (StartBit[BitCount] - (Col * BitCount mod 8));
Inc(Col, ColumnIncrement[Pass]);
Dec(CurBit, BitCount);
until CurBit < 0;
Inc(Src);
until Col >= Width;
end;
else
begin
Dst := @PByteArray(Data)[I * BytesPerLine + Col * BytesPerPixel];
repeat
CopyPixel(Src, Dst, BytesPerPixel);
Inc(Dst, BytesPerPixel);
Inc(Src, BytesPerPixel);
Inc(Dst, ColumnIncrement[Pass] * BytesPerPixel - BytesPerPixel);
Inc(Col, ColumnIncrement[Pass]);
until Col >= Width;
end;
end;
end;
procedure FilterScanline(Filter: Byte; BytesPerPixel: LongInt; Line, PrevLine, Target: PByteArray;
BytesPerLine: LongInt);
var
I: LongInt;
begin
case Filter of
0:
begin
// No filter
Move(Line^, Target^, BytesPerLine);
end;
1:
begin
// Sub filter
Move(Line^, Target^, BytesPerPixel);
for I := BytesPerPixel to BytesPerLine - 1 do
Target[I] := (Line[I] + Target[I - BytesPerPixel]) and $FF;
end;
2:
begin
// Up filter
for I := 0 to BytesPerLine - 1 do
Target[I] := (Line[I] + PrevLine[I]) and $FF;
end;
3:
begin
// Average filter
for I := 0 to BytesPerPixel - 1 do
Target[I] := (Line[I] + PrevLine[I] shr 1) and $FF;
for I := BytesPerPixel to BytesPerLine - 1 do
Target[I] := (Line[I] + (Target[I - BytesPerPixel] + PrevLine[I]) shr 1) and $FF;
end;
4:
begin
// Paeth filter
for I := 0 to BytesPerPixel - 1 do
Target[I] := (Line[I] + PaethPredictor(0, PrevLine[I], 0)) and $FF;
for I := BytesPerPixel to BytesPerLine - 1 do
Target[I] := (Line[I] + PaethPredictor(Target[I - BytesPerPixel], PrevLine[I], PrevLine[I - BytesPerPixel])) and $FF;
end;
end;
end;
procedure TransformLOCOToRGB(Data: PByte; NumPixels, BytesPerPixel: LongInt);
var
I: LongInt;
begin
for I := 0 to NumPixels - 1 do
begin
if IHDR.BitDepth = 8 then
begin
PColor32Rec(Data).R := Byte(PColor32Rec(Data).R + PColor32Rec(Data).G);
PColor32Rec(Data).B := Byte(PColor32Rec(Data).B + PColor32Rec(Data).G);
end
else
begin
PColor64Rec(Data).R := Word(PColor64Rec(Data).R + PColor64Rec(Data).G);
PColor64Rec(Data).B := Word(PColor64Rec(Data).B + PColor64Rec(Data).G);
end;
Inc(Data, BytesPerPixel);
end;
end;
function CheckBinaryPalette: Boolean;
begin
with GetLastFrame do
Result := (PaletteEntries = 2) and
(Palette[0].R = 0) and (Palette[0].G = 0) and (Palette[0].B = 0) and
(Palette[1].R = 255) and (Palette[1].G = 255) and (Palette[1].B = 255);
end;
begin
Image.Width := FrameWidth;
Image.Height := FrameHeight;
Image.Format := ifUnknown;
case IHDR.ColorType of
0:
begin
// Gray scale image
case IHDR.BitDepth of
1: Image.Format := ifBinary;
2, 4, 8: Image.Format := ifGray8;
16: Image.Format := ifGray16;
end;
BitCount := IHDR.BitDepth;
end;
2:
begin
// RGB image
case IHDR.BitDepth of
8: Image.Format := ifR8G8B8;
16: Image.Format := ifR16G16B16;
end;
BitCount := IHDR.BitDepth * 3;
end;
3:
begin
// Indexed image
if (IHDR.BitDepth = 1) and CheckBinaryPalette then
Image.Format := ifBinary
else
Image.Format := ifIndex8;
BitCount := IHDR.BitDepth;
end;
4:
begin
// Grayscale + alpha image
case IHDR.BitDepth of
8: Image.Format := ifA8Gray8;
16: Image.Format := ifA16Gray16;
end;
BitCount := IHDR.BitDepth * 2;
end;
6:
begin
// ARGB image
case IHDR.BitDepth of
8: Image.Format := ifA8R8G8B8;
16: Image.Format := ifA16R16G16B16;
end;
BitCount := IHDR.BitDepth * 4;
end;
end;
GetImageFormatInfo(Image.Format, Info);
BytesPerPixel := (BitCount + 7) div 8;
LineBuffer[True] := nil;
LineBuffer[False] := nil;
TotalBuffer := nil;
ZeroLine := nil;
ActLine := True;
// Start decoding
with Image do
try
BytesPerLine := (Width * BitCount + 7) div 8;
SrcDataSize := Height * BytesPerLine;