forked from mike-lischke/GraphicEx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphicEx.pas
10183 lines (8725 loc) · 345 KB
/
GraphicEx.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 GraphicEx;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
// The original code is GraphicEx.pas, released November 1, 1999.
//
// The initial developer of the original code is Mike Lischke (www.soft-gems.net),
//
// Copyright (C) 1999, 2008 Mike Lischke. All Rights Reserved.
//
// Credits:
// Haukur K. Bragason, Ingo Neumann, Craig Peterson
//----------------------------------------------------------------------------------------------------------------------
//
// See help file for a description of supported image formats.
//
// Version II.1.17
//
// Note: This library can be compiled with Delphi 5 or newer versions.
//
//----------------------------------------------------------------------------------------------------------------------
//
// September 2008
// - Bug fix: size computations in component retrieval for SGI images.
// October 2006
// - Bug fix: 16 bpp SGI images loading failed
// August 2005
// - Bug fix: added exceptions for PCX and PCD images in case they cannot be read.
// December 2005
// - Bug fix: The filter string returned for open dialogs was incorrect, which caused missing files in the dialog.
// November 2005
// - Bug fix: correct handling of 256 colors in PPM files.
// October 2005
// - Bug fix: Passing dynamic arrays of zero size to functions using the @ operator fails.
// February 2005
// - Bug fix: Line offset in TIFF did not consider partly used source bytes (BPP 4 and lower).
//
// January 2005:
// - Bug fix: color manager must be used for new TIFF reader.
// - Bug fix: CompBuffer in PSD loader must be set to nil initially.
// - Bug fix: DoStretch working bitmap is not thread safe, needs Canvas.Lock/Unlock.
// - Improvement: New standalone function ReadImageProperties.
//
// See help file for a full development history.
//
//----------------------------------------------------------------------------------------------------------------------
interface
{$I GraphicConfiguration.inc}
{$I Compilers.inc}
{$ifdef COMPILER_7_UP}
// For some things to work we need code, which is classified as being unsafe for .NET.
// We switch off warnings about that fact. We know it and we accept it.
{$warn UNSAFE_TYPE off}
{$warn UNSAFE_CAST off}
{$warn UNSAFE_CODE off}
{$endif COMPILER_7_UP}
uses
{$IFnDEF FPC}
Windows,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Classes, ExtCtrls, Graphics, SysUtils, Contnrs, JPG, TIFF,
GraphicCompression, GraphicStrings, GraphicColor;
const
GraphicExVersion = 'II.1.17';
type
TCardinalArray = array of Cardinal;
TByteArray = array of Byte;
TFloatArray = array of Single;
TImageOptions = set of (
ioTiled, // image consists of tiles not strips (TIF)
ioBigEndian, // byte order in values >= words is reversed (TIF, RLA, SGI)
ioMinIsWhite, // minimum value in grayscale palette is white not black (TIF)
ioReversed, // bit order in bytes is reveresed (TIF)
ioUseGamma // gamma correction is used
);
// describes the compression used in the image file
TCompressionType = (
ctUnknown, // Compression type is unknown.
ctNone, // No compression.
ctRLE, // Run length encoding.
ctPackedBits, // Macintosh packed bits.
ctLZW, // Lempel-Zif-Welch.
ctFax3, // CCITT T.4 (1D), also known as fax group 3.
ct2DFax3, // CCITT T.4 (2D).
ctFaxRLE, // Modified Huffman (CCITT T.4 derivative).
ctFax4, // CCITT T.6, also known as fax group 4.
ctFaxRLEW, // CCITT T.4 with word alignment.
ctLZ77, // Hufman inflate/deflate.
ctJPEG, // TIF JPEG compression (new version)
ctOJPEG, // TIF JPEG compression (old version)
ctThunderscan, // TIF thunderscan compression
ctNext,
ctIT8CTPAD,
ctIT8LW,
ctIT8MP,
ctIT8BL,
ctPixarFilm,
ctPixarLog,
ctDCS,
ctJBIG,
ctPCDHuffmann, // PhotoCD Hufman compression
ctPlainZip, // ZIP compression without prediction
ctPredictedZip, // ZIP comression with prediction
ctSGILog, // SGI Log Luminance RLE
ctSGILog24 // SGI Log 24-bit packed
);
// properties of a particular image which are set while loading an image or when
// they are explicitly requested via ReadImageProperties
PImageProperties = ^TImageProperties;
TImageProperties = record
Version: Cardinal; // TIF, PSP, GIF
Options: TImageOptions; // all images
Width, // all images
Height: Integer; // all images
ColorScheme: TColorScheme; // all images
BitsPerSample, // all Images
SamplesPerPixel, // all images
BitsPerPixel: Byte; // all images
Compression: TCompressionType; // all images
FileGamma: Single; // RLA, PNG
XResolution,
YResolution: Single; // given in dpi (TIF, PCX, PSP)
Interlaced, // GIF, PNG
HasAlpha: Boolean; // TIF, PNG
ImageCount: Cardinal; // Number of subimages (PCD, TIF, GIF, MNG).
Comment: string; // Implemented for PNG and GIF.
// Informational data, used internally and/or by decoders
// PCD
Overview: Boolean; // true if image is an overview image
Rotate: Byte; // describes how the image is rotated (aka landscape vs. portrait image)
// GIF
LocalColorTable: Boolean; // image uses an own color palette instead of the global one
// RLA
BottomUp: Boolean; // images is bottom to top
// PNG
FilterMode: Byte;
// TIFF
Orientation: Word;
end;
// This mode is used when creating a file mapping. See TFileMapping.
TFileMappingMode = (
fmmCreateNew, // Always create a new file (overwrite any existing). Implicitely gives read/write access.
fmmOpenOrCreate, // Open if file exists (implicitely gives read/write access) or create if it does not.
fmmReadOnly, // Open existing file read only.
fmmReadWrite // Open existing file with read and write access.
);
// This class is used to provide direct (mapped) memory access to a file.
// It is optimized for use in GraphicEx (sequential access).
TFileMapping = class
private
FFileName: string;
FFileHandle,
FFileMapping: THandle;
FFileSize: Int64;
FMemory: Pointer;
public
constructor Create(const FileName: string; Mode: TFileMappingMode); overload;
constructor Create(Stream: THandleStream); overload;
destructor Destroy; override;
property FileName: string read FFileName;
property Memory: Pointer read FMemory;
property Size: Int64 read FFileSize;
end;
// This is the base class for all image types implemented in GraphicEx.
// It contains some generally used stuff.
TGraphicExGraphic = class(TBitmap)
private
FColorManager: TColorManager;
FImageProperties: TImageProperties;
// Advanced progress display support.
FProgressStack: TStack; // Used to manage nested progress sections.
FProgressRect: TRect;
FPercentDone: Single; // Progress over all parts of the load process.
protected
Decoder: TDecoder; // The decoder used to decompress the image data.
procedure AdvanceProgress(Amount: Single; OffsetX, OffsetY: Integer; DoRedraw: Boolean);
procedure ClearProgressStack;
procedure FinishProgressSection(DoRedraw: Boolean);
procedure InitProgress(Width, Height: Integer);
procedure StartProgressSection(Size: Single; const S: string);
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function CanLoad(const FileName: string): Boolean; overload;
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; overload; virtual;
class function CanLoad(Stream: TStream): Boolean; overload;
procedure LoadFromFile(const FileName: string); override;
procedure LoadFromFileByIndex(const FileName: string; ImageIndex: Cardinal = 0);
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); virtual;
procedure LoadFromResourceID(Instance: THandle; ResID: Integer; ImageIndex: Cardinal = 0);
procedure LoadFromResourceName(Instance: THandle; const ResName: string; ImageIndex: Cardinal = 0);
procedure LoadFromStream(Stream: TStream); override;
procedure LoadFromStreamByIndex(Stream: TStream; ImageIndex: Cardinal = 0);
function ReadImageProperties(const Name: string; ImageIndex: Cardinal): Boolean; overload; virtual;
function ReadImageProperties(Stream: TStream; ImageIndex: Cardinal): Boolean; overload; virtual;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; overload; virtual;
property ColorManager: TColorManager read FColorManager;
property ImageProperties: TImageProperties read FImageProperties;
end;
TGraphicExGraphicClass = class of TGraphicExGraphic;
{$ifdef AutodeskGraphic}
// *.cel, *.pic images
TAutodeskGraphic = class(TGraphicExGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif AutodeskGraphic}
{$ifdef SGIGraphic}
// *.bw, *.rgb, *.rgba, *.sgi images
TSGIGraphic = class(TGraphicExGraphic)
private
FRowStart,
FRowSize: TCardinalArray; // Start and compressed length of the lines if the image is compressed.
procedure GetComponents(const Memory: Pointer; var Red, Green, Blue, Alpha: Pointer; Row: Integer);
procedure ReadAndDecode(const Memory: Pointer; Red, Green, Blue, Alpha: Pointer; Row: Integer; BPC: Cardinal);
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif SGIGraphic}
{$ifdef TIFFGraphic}
// *.tif, *.tiff images
TTIFFGraphic = class(TGraphicExGraphic)
private
FMemory: PByte;
FCurrentPointer: PByte;
FSize: Int64;
protected
procedure ReadContiguous(tif: PTIFF);
procedure ReadTiled(tif: PTIFF);
function SetOrientation(tif: PTIFF; H: Cardinal): Cardinal;
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size:Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$ifdef EPSGraphic}
TEPSGraphic = class(TTIFFGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(Stream: TStream; ImageIndex: Cardinal): Boolean; override;
end;
{$endif EPSGraphic}
{$endif TIFFGraphic}
{$ifdef TargaGraphic}
// *.tga; *.vst; *.icb; *.vda; *.win images
TTargaGraphic = class(TGraphicExGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
procedure SaveToStream(Stream: TStream); overload; override;
procedure SaveToStream(Stream: TStream; Compressed: Boolean); reintroduce; overload;
end;
{$endif TargaGraphic}
{$ifdef PCXGraphic}
// *.pcx; *.pcc; *.scr images
// Note: Due to the badly designed format a PCX/SCR file cannot be part in a larger stream because the position of the
// color palette as well as the decoding size can only be determined by the size of the image.
// Hence the image must be the only one in the stream or the last one.
TPCXGraphic = class(TGraphicExGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif PCXGraphic}
{$ifdef PCDGraphic}
// *.pcd images
// Note: By default the BASE resolution of a PCD image is loaded with LoadFromStream.
TPCDGraphic = class(TGraphicExGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 2); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif PCDGraphic}
{$ifdef PortableMapGraphic}
// *.ppm, *.pgm, *.pbm images
TPPMGraphic = class(TGraphicExGraphic)
private
FSource: PChar;
FRemainingSize: Int64;
function GetChar: Char;
function GetNumber: Cardinal;
function ReadLine: string;
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif PortableMapGraphic}
{$ifdef CUTGraphic}
// *.cut (+ *.pal) images
// Note: Also this format should not be used in a stream unless it is the only image or the last one!
TCUTGraphic = class(TGraphicExGraphic)
private
FPaletteFile: string;
protected
procedure LoadPalette;
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromFile(const FileName: string); override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
property PaletteFile: string read FPaletteFile write FPaletteFile;
end;
{$endif CUTGraphic}
{$ifdef GIFGraphic}
// *.gif images
TGIFGraphic = class(TGraphicExGraphic)
private
FSource: PByte;
FTransparentIndex: Byte;
function SkipExtensions: Byte;
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif GIFGraphic}
{$ifdef RLAGraphic}
// *.rla, *.rpf images
// Implementation based on code from Dipl. Ing. Ingo Neumann (ingo@delphingo.com).
TRLAGraphic = class(TGraphicExGraphic)
private
procedure SwapHeader(var Header); // start position of the image header in the stream
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif RLAGraphic}
{$ifdef PhotoshopGraphic}
// *.psd, *.pdd images
TPSDLayerBlendMode = (
lbmNormal,
lbmDarken,
lbmLighten,
lbmHue,
lbmSaturation,
lbmColor,
lbmLuminosity,
lbmMultiply,
lbmScreen,
lbmDissolve,
lbmOverlay,
lbmHardLight,
lbmSoftLight,
lbmDifference,
lbmExclusion,
lbmColorDodge,
lbmColorBurn
);
TPSDLayerClipping = (
lcBase,
lcNonBase
);
TPSDLayerOptions = set of (
loTransparencyProtected,
loHidden,
loIrrelevantData
);
TPSDLayerType = (
ltBitmap,
ltText,
ltMask
);
// Flags used for mask data in a Photoshop layer.
TPSDLayerMaskFlags = set of (
lmfRelativePosition, // Position of mask is relative to layer.
lmfMaskDisabled, // The layer mask is disabled.
lmfInvertMask // Invert layer mask when blending.
);
TPSDLayerMaskData = record
Bounds: TRect;
DefaultColor: Byte;
Flags: TPSDLayerMaskFlags;
UserMaskBackground: Byte;
end;
// Currently no info is available for data in this block.
TPSDCompositeGrayBlend = record
Black1,
Black2,
White1,
White2: Byte;
end;
// Data specific to one channel in a layer.
// Pixel data is not stored separately for each channel but the layer as a whole.
TPSDChannel = record
ChannelID: SmallInt;
Size: Cardinal; // Size of channel data when loading or storing.
BlendSourceRange,
BlendTargetRange: TPSDCompositeGrayBlend;
Data: Pointer; // Temporary storage for the channel's pixel data.
end;
// Each layer has a collection of channel data.
TPSDChannels = array of TPSDChannel;
// Indirect type declaration here to allow recursive item data structure.
PPSDItemList = ^TPSDItemList;
PPSDDescriptor = ^TPSDDescriptor;
TPSDItemData = record
ItemType: Cardinal; // Type of the item. See ReadDescriptor for a list of possible values.
ClassID: WideString; // Only valid if property or class item.
KeyID: WideString; // Only valid if property or string item.
Name: WideString; // Only valid if name or identifier item.
Units: Integer; // Only valid if Unit float item.
Value: Double; // Only valid if Unit float or double item.
TypeID: WideString; // Only valid if enumeration item.
EnumValue: WideString; // Only valid if enumeration item.
Offset: Cardinal; // Only valid if offset item.
IntValue: Integer; // Only valid if integer item.
BoolValue: Boolean; // Only valid if boolean item.
List: PPSDItemList; // Only valid if (reference) list or item.
DataSize: Cardinal; // Only valid if raw data.
Data: Pointer; // Only valid if raw data.
Descriptor: PPSDDescriptor; // Only valid if the item is again a PSD descriptor.
end;
TPSDItemList = array of TPSDItemData;
// One entry in a PSD descriptor stored as part of e.g. the type tool adjustment layer.
TPSDDescriptorItem = record
Key: string; // Item name.
Data: TPSDItemData; // The value of the item.
end;
TPSDDescriptor = record
ClassID,
ClassID2: WideString;
Items: array of TPSDDescriptorItem;
end;
TDoubleRect = record
Left, Top, Right, Bottom: Double;
end;
TTypeTransform = record
XX, XY, YX, YY, TX, TY: Double;
end;
TPSDTypeToolInfo = record
Transform: TTypeTransform;
TextDescriptor,
WarpDescriptor: TPSDDescriptor;
WarpRectangle: TDoubleRect;
end;
TPSDGraphic = class;
TPhotoshopLayer = class
private
FGraphic: TPSDGraphic;
FBounds: TRect;
FBlendMode: TPSDLayerBlendMode;
FOpacity: Byte; // 0 = transparent ... 255 = opaque
FClipping: TPSDLayerClipping;
FOptions: TPSDLayerOptions;
FMaskData: TPSDLayerMaskData;
FCompositeGrayBlendSource,
FCompositeGrayBlendDestination: TPSDCompositeGrayBlend;
FChannels: TPSDChannels;
FName: WideString;
FImage: TBitmap;
FType: TPSDLayerType;
FTypeToolInfo: TPSDTypeToolInfo; // Only valid if layer is a text layer.
procedure SetImage(const Value: TBitmap);
public
constructor Create(Graphic: TPSDGraphic);
destructor Destroy; override;
property BlendMode: TPSDLayerBlendMode read FBlendMode write FBlendMode;
property Bounds: TRect read FBounds write FBounds;
property Channels: TPSDChannels read FChannels write FChannels;
property Clipping: TPSDLayerClipping read FClipping write FClipping;
property CompositeGrayBlendDestination: TPSDCompositeGrayBlend read FCompositeGrayBlendDestination
write FCompositeGrayBlendDestination;
property CompositeGrayBlendSource: TPSDCompositeGrayBlend read FCompositeGrayBlendSource
write FCompositeGrayBlendSource;
property Image: TBitmap read FImage write SetImage;
property LayerType: TPSDLayerType read FType;
property MaskData: TPSDLayerMaskData read FMaskData write FMaskData;
property Name: WideString read FName write FName;
property Opacity: Byte read FOpacity write FOpacity;
property Options: TPSDLayerOptions read FOptions write FOptions;
end;
TPhotoshopLayers = class(TList)
private
FGraphic: TPSDGraphic;
// The following fields are read from the global layer mask info data but
// their meaning is not well documented or at least obvious from their names.
FOverlayColorSpace: Word; // undocumented
FColorComponents: array[0..3] of Word; // undocumented
FLayerMaskOpacity: Word; // 0 = transparent, 100 = opaque
FKind: Byte; // 0 = Color selected, 1 = Color protected, 128 = use value stored per layer.
// The last one is preferred. The others are for backward compatibility.
protected
function Get(Index: Integer): TPhotoshopLayer;
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
procedure Put(Index: Integer; Layer: TPhotoshopLayer);
public
constructor Create(Graphic: TPSDGraphic);
function Add(Layer: TPhotoshopLayer): Integer;
function AddNewLayer: TPhotoshopLayer;
function Extract(Layer: TPhotoshopLayer): TPhotoshopLayer;
function First: TPhotoshopLayer;
function IndexOf(Layer: TPhotoshopLayer): Integer;
procedure Insert(Index: Integer; Layer: TPhotoshopLayer);
function Last: TPhotoshopLayer;
function Remove(Layer: TPhotoshopLayer): Integer;
property Items[Index: Integer]: TPhotoshopLayer read Get write Put; default;
end;
TPSDGuide = record
Location: Single; // Either X or Y coordinate of the guide depending on IsHorizontal.
IsHorizontal: Boolean; // True if it is a horizontal guide, otherwise False.
end;
TPSDGridSettings = record
HorizontalCycle, // Number of dots per cycle relative to 72 dpi.
VerticalCycle: Single;
Guides: array of TPSDGuide;
end;
TPSDGraphic = class(TGraphicExGraphic)
private
FChannels, // Original channel count of the image (1..24).
FMode: Word; // Original color mode of the image (PSD_*).
FLayers: TPhotoshopLayers;
FGridSettings: TPSDGridSettings;
protected
procedure CombineChannels(Layer: TPhotoshopLayer);
function ConvertCompression(Value: Word): TCompressionType;
function DetermineColorScheme(ChannelCount: Integer): TColorScheme;
procedure LoadAdjustmentLayer(var Run: PAnsiChar; Layer: TPhotoshopLayer);
procedure ReadChannelData(var Run: PAnsiChar; var Channel: TPSDChannel; Width, Height: Integer; IsIrrelevant: Boolean);
procedure ReadDescriptor(var Run: PAnsiChar; var Descriptor: TPSDDescriptor);
procedure ReadMergedImage(var Source: PAnsiChar; Layer: TPhotoshopLayer; Compression: TCompressionType; Channels: Byte);
procedure ReadLayers(Run: PAnsiChar);
procedure ReadResources(Run: PAnsiChar);
function SetupColorManager(Channels: Integer): TPixelFormat;
public
constructor Create; override;
destructor Destroy; override;
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
property GridSettings: TPSDGridSettings read FGridSettings;
property Layers: TPhotoshopLayers read FLayers;
end;
{$endif PhotoshopGraphic}
{$ifdef PaintshopProGraphic}
// *.psp images (file version 3 and 4)
TPSPGraphic = class(TGraphicExGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif PaintshopProGraphic}
{$ifdef PortableNetworkGraphic}
// *.png images
TChunkType = array[0..3] of AnsiChar;
// This header is followed by a variable number of data bytes, which are followed by the CRC for this data.
// The actual size of this data is given by field length in the chunk header.
// CRC is Cardinal (4 byte unsigned integer).
TPNGChunkHeader = packed record
Length: Cardinal; // size of data (entire chunk excluding itself, CRC and type)
ChunkType: TChunkType;
end;
TPNGGraphic = class(TGraphicExGraphic)
private
FIDATSize: Integer; // remaining bytes in the current IDAT chunk
FRawBuffer, // buffer to load raw chunk data and to check CRC
FCurrentSource: Pointer; // points into FRawBuffer for current position of decoding
FHeader: TPNGChunkHeader; // header of the current chunk
FCurrentCRC: Cardinal; // running CRC for the current chunk
FSourceBPP: Integer; // bits per pixel used in the file
FPalette: HPALETTE; // used to hold the palette handle until we can set it finally after the pixel format
// has been set too (as this destroys the current palette)
FTransparency: TByteArray; // If the image is indexed then this array might contain alpha values (depends on file)
// each entry corresponding to the same palette index as the index in this array.
// For grayscale and RGB images FTransparentColor contains the (only) transparent
// color.
FTransparentColor: TColor; // transparent color for gray and RGB
FBackgroundColor: TColor; // index or color ref
procedure ApplyFilter(Filter: Byte; Line, PrevLine, Target: PByte; BPP, BytesPerRow: Integer);
function IsChunk(ChunkType: TChunkType): Boolean;
function LoadAndSwapHeader(var Source: PByte): Cardinal;
procedure LoadBackgroundColor(var Source: PByte; const Description);
procedure LoadIDAT(var Source: PByte; const Description);
procedure LoadText(var Source: PByte);
procedure LoadTransparency(var Source: PByte; const Description);
procedure ReadDataAndCheckCRC(var Source: PByte);
procedure ReadRow(var Source: PByte; RowBuffer: Pointer; BytesPerRow: Integer);
function SetupColorDepth(ColorType, BitDepth: Integer): Integer;
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
property BackgroundColor: TColor read FBackgroundColor;
property Transparency: TByteArray read FTransparency;
end;
{$endif PortableNetworkGraphic}
{$ifdef ArtsAndLettersGraphic}
// *.ged images (Arts & Letters images)
TGEDGraphic = class(TGraphicExGraphic)
public
class function CanLoad(const Memory: Pointer; Size: Int64): Boolean; override;
procedure LoadFromMemory(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal = 0); override;
function ReadImageProperties(const Memory: Pointer; Size: Int64; ImageIndex: Cardinal): Boolean; override;
end;
{$endif ArtsAndLettersGraphic}
// ---------- file format management stuff
TFormatType = (
ftAnimation, // format contains an animation (like GIF or AVI)
ftLayered, // format supports multiple layers (like PSP, PSD)
ftMultiImage, // format can contain more than one image (like TIF or GIF)
ftRaster, // format is contains raster data (this is mainly used)
ftVector // format contains vector data (like DXF or PSP file version 4)
);
TFormatTypes = set of TFormatType;
TFilterSortType = (
fstNone, // do not sort entries, list them as they are registered
fstBoth, // sort entries first by description then by extension
fstDescription, // sort entries by description only
fstExtension // sort entries by extension only
);
TFilterOption = (
foCompact, // use the compact form in filter strings instead listing each extension on a separate line
foIncludeAll, // include the 'All image files' filter string
foIncludeExtension // add the extension to the description
);
TFilterOptions = set of TFilterOption;
// The file format list is an alternative to Delphi's own poor implementation which does neither allow to filter
// graphic formats nor to build common entries in filter strings nor does it care for duplicate entries or
// alphabetic ordering. Additionally, some properties are maintained for each format to do searches, filter particular
// formats for a certain case etc.
TFileFormatList = class
private
FClassList,
FExtensionList: TList;
protected
function FindExtension(const Extension: string): Integer;
function FindGraphicClass(GraphicClass: TGraphicClass): Integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function GetDescription(Graphic: TGraphicClass): string;
procedure GetExtensionList(List: TStrings);
function GetGraphicFilter(Formats: TFormatTypes; SortType: TFilterSortType; Options: TFilterOptions;
GraphicClass: TGraphicClass): string;
function GraphicFromExtension(S: string): TGraphicClass;
function GraphicFromContent(const FileName: string): TGraphicExGraphicClass; overload;
function GraphicFromContent(const Memory: Pointer; Size: Int64): TGraphicExGraphicClass; overload;
function GraphicFromContent(Stream: TStream): TGraphicExGraphicClass; overload;
procedure RegisterFileFormat(const Extension, Common, Individual: string; FormatTypes: TFormatTypes;
Replace: Boolean; GraphicClass: TGraphicClass);
procedure UnregisterFileFormat(const Extension: string; GraphicClass: TGraphicClass);
end;
// Resampling support types.
TResamplingFilter = (
sfBox,
sfTriangle,
sfHermite,
sfBell,
sfSpline,
sfLanczos3,
sfMitchell
);
procedure GraphicExError(ErrorString: string); overload;
procedure GraphicExError(ErrorString: string; Args: array of const); overload;
// Resampling support routines.
procedure Stretch(NewWidth, NewHeight: Cardinal; Filter: TResamplingFilter; Radius: Single; Source, Target: TBitmap); overload;
procedure Stretch(NewWidth, NewHeight: Cardinal; Filter: TResamplingFilter; Radius: Single; Source: TBitmap); overload;
function ReadImageProperties(const FileName: string; var Properties: TImageProperties): Boolean;
var
FileFormatList: TFileFormatList;
//----------------------------------------------------------------------------------------------------------------------
implementation
uses
{$IFnDEF FPC}
Consts,
{$ELSE}
IntfGraphics,
{$ENDIF}
Math, MZLib;
type
{$ifndef COMPILER_6_UP}
PCardinal = ^Cardinal;
{$endif COMPILER_6_UP}
// resampling support types
TRGBInt = record
R, G, B: Integer;
end;
TRGBAInt = record
R, G, B, A: Integer;
end;
PRGBWord = ^TRGBWord;
TRGBWord = record
R, G, B: Word;
end;
PRGBAWord = ^TRGBAWord;
TRGBAWord = record
R, G, B, A: Word;
end;
PBGR = ^TBGR;
TBGR = packed record
B, G, R: Byte;
end;
PBGRA = ^TBGRA;
TBGRA = packed record
B, G, R, A: Byte;
end;
PRGB = ^TRGB;
TRGB = packed record
R, G, B: Byte;
end;
PRGBA = ^TRGBA;
TRGBA = packed record
R, G, B, A: Byte;
end;
PPixelArray = ^TPixelArray;
TPixelArray = array[0..0] of TBGR;
TFilterFunction = function(Value: Single): Single;
// contributor for a Pixel
PContributor = ^TContributor;
TContributor = record
Weight: Integer; // Pixel Weight
Pixel: Integer; // Source Pixel
end;
TContributors = array of TContributor;
// list of source pixels contributing to a destination pixel
TContributorEntry = record
N: Integer;
Contributors: TContributors;
end;
TContributorList = array of TContributorEntry;
// An entry of the progress stack for nested progress sections.
PProgressSection = ^TProgressSection;
TProgressSection = record
Position, // Current position in percent.
ParentSize, // Size of this section in the context of the parent section (in %).
TransformFactor: Single; // Accumulated factor to transform a step in this section to an overall value.
Message: string; // Message to display for this section.
end;
const
DefaultFilterRadius: array[TResamplingFilter] of Single = (0.5, 1, 1, 1.5, 2, 3, 2);
threadvar // globally used cache for current image (speeds up resampling about 10%)
CurrentLineR: array of Integer;
CurrentLineG: array of Integer;
CurrentLineB: array of Integer;
CurrentLineA: array of Integer;
//----------------------------------------------------------------------------------------------------------------------
{$ifndef COMPILER_6_UP}
procedure RaiseLastOSError;
begin
RaiseLastWin32Error;
end;
{$endif}
//----------------------------------------------------------------------------------------------------------------------
procedure GraphicExError(ErrorString: string); overload;
begin
raise EInvalidGraphic.Create(ErrorString);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure GraphicExError(ErrorString: string; Args: array of const); overload;
begin
raise EInvalidGraphic.CreateFmt(ErrorString, Args);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure Upsample(Width, Height, ScaledWidth: Cardinal; Pixels: PChar);
// Creates a new image that is a integral size greater than an existing one.
var
X, Y: Cardinal;
P, Q, R: PChar;
begin
for Y := 0 to Height - 1 do
begin
P := Pixels + (Height - 1 - Y) * ScaledWidth + (Width - 1);
Q := Pixels + ((Height - 1 - Y) shl 1) * ScaledWidth + ((Width - 1) shl 1);
Q^ := P^;
(Q + 1)^ := P^;
for X := 1 to Width - 1 do
begin
Dec(P);
Dec(Q, 2);
Q^ := P^;
(Q + 1)^ := Char((Word(P^) + Word((P + 1)^) + 1) shr 1);
end;
end;
for Y := 0 to Height - 2 do
begin
P := Pixels + (Y shl 1) * ScaledWidth;
Q := P + ScaledWidth;
R := Q + ScaledWidth;
for X := 0 to Width - 2 do
begin
Q^ := Char((Word(P^) + Word(R^) + 1) shr 1);
(Q + 1)^ := Char((Word(P^) + Word((P + 2)^) + Word(R^) + Word((R + 2)^) + 2) shr 2);
Inc(Q, 2);
Inc(P, 2);
Inc(R, 2);
end;
Q^ := Char((Word(P^) + Word(R^) + 1) shr 1);
Inc(P);
Inc(Q);
Q^ := Char((Word(P^) + Word(R^) + 1) shr 1);
end;
P := Pixels + (2 * Height - 2) * ScaledWidth;
Q := Pixels + (2 * Height - 1) * ScaledWidth;
Move(P^, Q^, 2 * Width);
end;
//----------------- filter functions for stretching --------------------------------------------------------------------
function HermiteFilter(Value: Single): Single;
// f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1
begin
if Value < 0 then
Value := -Value;
if Value < 1 then
Result := (2 * Value - 3) * Sqr(Value) + 1
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function BoxFilter(Value: Single): Single;
// This filter is also known as 'nearest neighbour' Filter.
begin
if (Value > -0.5) and (Value <= 0.5) then
Result := 1
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function TriangleFilter(Value: Single): Single;
// aka 'linear' or 'bilinear' filter
begin
if Value < 0 then
Value := -Value;
if Value < 1 then
Result := 1 - Value
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function BellFilter(Value: Single): Single;
begin
if Value < 0 then
Value := -Value;
if Value < 0.5 then
Result := 0.75 - Sqr(Value)
else
if Value < 1.5 then
begin
Value := Value - 1.5;
Result := 0.5 * Sqr(Value);
end
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function SplineFilter(Value: Single): Single;
// B-spline filter
var
Temp: Single;
begin
if Value < 0 then