-
Notifications
You must be signed in to change notification settings - Fork 12
/
bgrabitmaptypes.pas
1248 lines (1087 loc) · 44 KB
/
bgrabitmaptypes.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
{ ***************************************************************************
* *
* This file is part of BGRABitmap library which is distributed under the *
* modified LGPL. *
* *
* See the file COPYING.modifiedLGPL.txt, included in this distribution, *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
************************* BGRABitmap library ******************************
- Drawing routines with transparency and antialiasing with Lazarus.
Offers also various transforms.
- These routines allow to manipulate 32bit images in BGRA format or RGBA
format (depending on the platform).
- This code is under modified LGPL (see COPYING.modifiedLGPL.txt).
This means that you can link this library inside your programs for any purpose.
Only the included part of the code must remain LGPL.
- If you make some improvements to this library, please notify here:
http://www.lazarus.freepascal.org/index.php/topic,12037.0.html
********************* Contact : Circular at operamail.com *******************
******************************* CONTRIBUTOR(S) ******************************
- Edivando S. Santos Brasil | [email protected]
(Compatibility with FPC ($Mode objfpc/delphi) and delphi VCL 11/2018)
***************************** END CONTRIBUTOR(S) *****************************}
Unit BGRABitmapTypes;
{$i bgrabitmap.inc}{$H+}
interface
uses
Classes, Types,
{$IFDEF FPC}
FPImgCanv{$IFDEF BGRABITMAP_USE_LCL}, LCLType, GraphType{$ENDIF},
{$ELSE}
System.ConvUtils, System.VarUtils, System.UITypes, FPImgCanv, GraphType,
{$ENDIF}
BGRAGraphics, FPImage, BGRATypes, BGRAMultiFileType;
type
TMultiFileContainer = BGRAMultiFileType.TMultiFileContainer;
Int32or64 = {$IFDEF CPU64}BGRAInt64{$ELSE}Integer{$ENDIF}; //BGRALongInt
UInt32or64 = {$IFDEF CPU64}BGRAUInt64{$ELSE}BGRALongWord{$ENDIF};
TArrayWord = packed array of BGRAWord;
{=== Miscellaneous types ===}
type
{* Options when doing a floodfill (also called bucket fill) }
TFloodfillMode = (
{** Pixels that are filled are replaced }
fmSet,
{** Pixels that are filled are drawn upon with the fill color }
fmDrawWithTransparency,
{** Pixels that are filled are drawn upon to the extent that the color underneath is similar to
the start color. The more different the different is, the less it is drawn upon }
fmProgressive);
{* Specifies how much smoothing is applied to the computation of the median }
TMedianOption = (moNone, moLowSmooth, moMediumSmooth, moHighSmooth);
{* Specifies the shape of a predefined blur }
TRadialBlurType = (
{** Gaussian-like, pixel importance decreases progressively }
rbNormal,
{** Disk blur, pixel importance does not decrease progressively }
rbDisk,
{** Pixel are considered when they are at a certain distance }
rbCorona,
{** Gaussian-like, but 10 times smaller than ''rbNormal'' }
rbPrecise,
{** Gaussian-like but simplified to be computed faster }
rbFast,
{** Box blur, pixel importance does not decrease progressively
and the pixels are included when they are in a square.
This is much faster than ''rbFast'' however you may get
square shapes in the resulting image }
rbBox);
TEmbossOption = (eoTransparent, eoPreserveHue);
TEmbossOptions = set of TEmbossOption;
TTextLayout = BGRAGraphics.TTextLayout;
TFontBidiMode = (fbmAuto, fbmLeftToRight, fbmRightToLeft);
TBidiTextAlignment = (btaNatural, btaOpposite, btaLeftJustify, btaRightJustify, btaCenter);
const
RadialBlurTypeToStr: array[TRadialBlurType] of string =
('Normal','Disk','Corona','Precise','Fast','Box');
tlTop = BGRAGraphics.tlTop;
tlCenter = BGRAGraphics.tlCenter;
tlBottom = BGRAGraphics.tlBottom;
// checks the bounds of an image in the given clipping rectangle
function CheckPutImageBounds(x, y, tx, ty: integer; out minxb, minyb, maxxb, maxyb, ignoreleft: integer; const cliprect: TRect): boolean;
{==== Imported from GraphType ====}
//if this unit is defined, otherwise
//define here the types used by the library.
{$IFDEF BGRABITMAP_USE_LCL}
type
{ Order of the lines in an image }
TRawImageLineOrder = GraphType.TRawImageLineOrder;
{ Order of the bits in a byte containing pixel values }
TRawImageBitOrder = GraphType.TRawImageBitOrder;
{ Order of the bytes in a group of byte containing pixel values }
TRawImageByteOrder = GraphType.TRawImageByteOrder;
{ Definition of a single line 3D bevel }
TGraphicsBevelCut = GraphType.TGraphicsBevelCut;
const
riloTopToBottom = GraphType.riloTopToBottom; // The first line (line 0) is the top line
riloBottomToTop = GraphType.riloBottomToTop; // The first line (line 0) is the bottom line
riboBitsInOrder = GraphType.riboBitsInOrder; // Bit 0 is pixel 0
riboReversedBits = GraphType.riboReversedBits; // Bit 0 is pixel 7 (Bit 1 is pixel 6, ...)
riboLSBFirst = GraphType.riboLSBFirst; // least significant byte first (little endian)
riboMSBFirst = GraphType.riboMSBFirst; // most significa['{A55746D2-1C7E-4D74-9DF0-D32590AE0EFF}']nt byte first (big endian)
fsSurface = GraphType.fsSurface; //type is defined as Graphics.TFillStyle
fsBorder = GraphType.fsBorder;
{$IFDEF FPC}
bvNone = GraphType.bvNone;
bvLowered = GraphType.bvLowered;
bvRaised = GraphType.bvRaised;
bvSpace = GraphType.bvSpace;
{$ENDIF}
{$ELSE}
type
{* Order of the lines in an image }
TRawImageLineOrder = (
{** The first line in memory (line 0) is the top line }
riloTopToBottom,
{** The first line in memory (line 0) is the bottom line }
riloBottomToTop);
{* Order of the bits in a byte containing pixel values }
TRawImageBitOrder = (
{** The lowest bit is on the left. So with a monochrome picture, bit 0 would be pixel 0 }
riboBitsInOrder,
{** The lowest bit is on the right. So with a momochrome picture, bit 0 would be pixel 7 (bit 1 would be pixel 6, ...) }
riboReversedBits);
{* Order of the bytes in a group of byte containing pixel values }
TRawImageByteOrder = (
{** Least significant byte first (little endian) }
riboLSBFirst,
{** most significant byte first (big endian) }
riboMSBFirst);
{* Definition of a single line 3D bevel }
TGraphicsBevelCut =
(
{** No bevel }
bvNone,
{** Shape is lowered, light is on the bottom-right corner }
bvLowered,
{** Shape is raised, light is on the top-left corner }
bvRaised,
{** Shape is at the same level, there is no particular lighting }
bvSpace);
{$ENDIF}
{$DEFINE INCLUDE_INTERFACE}
{$I bgrapixel.inc}
{$DEFINE INCLUDE_INTERFACE}
{$I geometrytypes.inc}
{$DEFINE INCLUDE_INTERFACE}
{$i csscolorconst.inc}
type
{$DEFINE INCLUDE_SCANNER_INTERFACE }
{$I bgracustombitmap.inc}
{==== Types provided for fonts ====}
{* Quality to be used to render text }
TBGRAFontQuality = (
{** Use the system capabilities. It is rather fast however it may be
not be smoothed. }
fqSystem,
{** Use the system capabilities to render with ClearType. This quality is
of course better than fqSystem however it may not be perfect.}
fqSystemClearType,
{** Garanties a high quality antialiasing. }
fqFineAntialiasing,
{** Fine antialiasing with ClearType in assuming an LCD display in red/green/blue order }
fqFineClearTypeRGB,
{** Fine antialiasing with ClearType in assuming an LCD display in blue/green/red order }
fqFineClearTypeBGR);
{* Measurements of a font }
TFontPixelMetric = record
{** The values have been computed }
Defined: boolean;
{** Position of the baseline, where most letters lie }
Baseline,
{** Position of the top of the small letters (x being one of them) }
xLine,
{** Position of the top of the UPPERCASE letters }
CapLine,
{** Position of the bottom of letters like g and p }
DescentLine,
{** Total line height including line spacing defined by the font }
Lineheight: integer;
end;
{* Vertical anchoring of the font. When text is drawn, a start coordinate
is necessary. Text can be positioned in different ways. This enum
defines what position it is regarding the font }
TFontVerticalAnchor = (
{** The top of the font. Everything will be drawn below the start coordinate. }
fvaTop,
{** The center of the font }
fvaCenter,
{** The top of capital letters }
fvaCapLine,
{** The center of capital letters }
fvaCapCenter,
{** The top of small letters }
fvaXLine,
{** The center of small letters }
fvaXCenter,
{** The baseline, the bottom of most letters }
fvaBaseline,
{** The bottom of letters that go below the baseline }
fvaDescentLine,
{** The bottom of the font. Everything will be drawn above the start coordinate }
fvaBottom);
{* Definition of a function that handles work-break }
TWordBreakHandler = procedure(var ABeforeUTF8, AAfterUTF8: string) of object;
{* Alignment for a typewriter, that does not have any more information
than a square shape containing glyphs }
TBGRATypeWriterAlignment = (twaTopLeft, twaTop, twaTopRight, twaLeft, twaMiddle, twaRight, twaBottomLeft, twaBottom, twaBottomRight);
{* How a typewriter must render its content on a Canvas2d }
TBGRATypeWriterOutlineMode = (twoPath, twoFill, twoStroke, twoFillOverStroke, twoStrokeOverFill, twoFillThenStroke, twoStrokeThenFill);
{ TBGRACustomFontRenderer }
{* Abstract class for all font renderers }
TBGRACustomFontRenderer = class
{** Specifies the font to use. Unless the font renderer accept otherwise,
the name is in human readable form, like 'Arial', 'Times New Roman', ... }
FontName: string;
{** Specifies the set of styles to be applied to the font.
These can be fsBold, fsItalic, fsStrikeOut, fsUnderline.
So the value [fsBold,fsItalic] means that the font must be bold and italic }
FontStyle: TFontStyles;
{** Specifies the quality of rendering. Default value is fqSystem }
FontQuality : TBGRAFontQuality;
{** Specifies the rotation of the text, for functions that support text rotation.
It is expressed in tenth of degrees, positive values going counter-clockwise }
FontOrientation: integer;
{** Specifies the height of the font without taking into account additional line spacing.
A negative value means that it is the full height instead }
FontEmHeight: integer;
{** Returns measurement for the current font in pixels }
function GetFontPixelMetric: TFontPixelMetric; virtual; abstract;
{** Returns the total size of the string provided using the current font.
Orientation is not taken into account, so that the width is along the text }
function TextSize(sUTF8: string): TSize; overload; virtual; abstract;
function TextSize(sUTF8: string; AMaxWidth: integer; ARightToLeft: boolean): TSize; overload; virtual; abstract;
function TextFitInfo(sUTF8: string; AMaxWidth: integer): integer; virtual; abstract;
function TextSizeAngle(sUTF8: string; {%H-}orientationTenthDegCCW: integer): TSize; virtual;
{** Draws the UTF8 encoded string, with color ''c''.
If align is taLeftJustify, (''x'',''y'') is the top-left corner.
If align is taCenter, (''x'',''y'') is at the top and middle of the text.
If align is taRightJustify, (''x'',''y'') is the top-right corner.
The value of ''FontOrientation'' is taken into account, so that the text may be rotated }
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; c: TBGRAPixel; align: TAlignment); overload; virtual; abstract;
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; c: TBGRAPixel; align: TAlignment; {%H-}ARightToLeft: boolean); overload; virtual;
{** Same as above functions, except that the text is filled using texture.
The value of ''FontOrientation'' is taken into account, so that the text may be rotated }
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; texture: IBGRAScanner; align: TAlignment); overload; virtual; abstract;
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; texture: IBGRAScanner; align: TAlignment; {%H-}ARightToLeft: boolean); overload; virtual;
{** Same as above, except that the orientation is specified, overriding the value of the property ''FontOrientation'' }
procedure TextOutAngle(ADest: TBGRACustomBitmap; x, y: single; orientationTenthDegCCW: integer; sUTF8: string; c: TBGRAPixel; align: TAlignment); overload; virtual; abstract;
{** Same as above, except that the orientation is specified, overriding the value of the property ''FontOrientation'' }
procedure TextOutAngle(ADest: TBGRACustomBitmap; x, y: single; orientationTenthDegCCW: integer; sUTF8: string; texture: IBGRAScanner; align: TAlignment); overload; virtual; abstract;
{** Draw the UTF8 encoded string at the coordinate (''x'',''y''), clipped inside the rectangle ''ARect''.
Additional style information is provided by the style parameter.
The color ''c'' is used to fill the text. No rotation is applied. }
procedure TextRect(ADest: TBGRACustomBitmap; ARect: TRect; x, y: integer; sUTF8: string; style: TTextStyle; c: TBGRAPixel); overload; virtual; abstract;
{** Same as above except a ''texture'' is used to fill the text }
procedure TextRect(ADest: TBGRACustomBitmap; ARect: TRect; x, y: integer; sUTF8: string; style: TTextStyle; texture: IBGRAScanner); overload; virtual; abstract;
{** Copy the path for the UTF8 encoded string into ''ADest''.
If ''align'' is ''taLeftJustify'', (''x'',''y'') is the top-left corner.
If ''align'' is ''taCenter'', (''x'',''y'') is at the top and middle of the text.
If ''align'' is ''taRightJustify'', (''x'',''y'') is the top-right corner. }
procedure CopyTextPathTo({%H-}ADest: IBGRAPath; {%H-}x, {%H-}y: Single; {%H-}s: string; {%H-}align: TAlignment); virtual; //optional
end;
{* Output mode for the improved renderer for readability. This is used by the font renderer based on LCL in ''BGRAText'' }
TBGRATextOutImproveReadabilityMode = (irMask, irNormal, irClearTypeRGB, irClearTypeBGR);
{==== Images and resampling ====}
//type
{* How the resample is to be computed }
TResampleMode = (
{** Low quality resample by repeating pixels, stretching them }
rmSimpleStretch,
{** Use resample filters. This gives high
quality resampling however this the proportion changes slightly because
the first and last pixel are considered to occupy only half a unit as
they are considered as the border of the picture
(pixel-centered coordinates) }
rmFineResample);
{* List of resample filter to be used with ''rmFineResample'' }
TResampleFilter = (
{** Equivalent of simple stretch with high quality and pixel-centered coordinates }
rfBox,
{** Linear interpolation giving slow transition between pixels }
rfLinear,
{** Mix of ''rfLinear'' and ''rfCosine'' giving medium speed stransition between pixels }
rfHalfCosine,
{** Cosine-like interpolation giving fast transition between pixels }
rfCosine,
{** Simple bi-cubic filter (blurry) }
rfBicubic,
{** Mitchell filter, good for downsizing interpolation }
rfMitchell,
{** Spline filter, good for upsizing interpolation, however slightly blurry }
rfSpline,
{** Lanczos with radius 2, blur is corrected }
rfLanczos2,
{** Lanczos with radius 3, high contrast }
rfLanczos3,
{** Lanczos with radius 4, high contrast }
rfLanczos4,
{** Best quality using rfMitchell or rfSpline }
rfBestQuality);
//type
{* List of image formats }
TBGRAImageFormat = (
{** Unknown format }
ifUnknown,
{** JPEG format, opaque, lossy compression }
ifJpeg,
{** PNG format, transparency, lossless compression }
ifPng,
{** GIF format, Single transparent color, lossless in theory but only low number of colors allowed }
ifGif,
{** BMP format, transparency, no compression. Note that transparency is
not supported by all BMP readers so it is not recommended to avoid
storing images with transparency in this format }
ifBmp,
{** iGO BMP (16-bit, rudimentary lossless compression) }
ifBmpMioMap,
{** ICO format, contains different sizes of the same image }
ifIco,
{** CUR format, has hotspot, contains different sizes of the same image }
ifCur,
{** PCX format, opaque, rudimentary lossless compression }
ifPcx,
{** Paint.NET format, layers, lossless compression }
ifPaintDotNet,
{** LazPaint format, layers, lossless compression }
ifLazPaint,
{** OpenRaster format, layers, lossless compression }
ifOpenRaster,
{** Phoxo format, layers }
ifPhoxo,
{** Photoshop format, layers, rudimentary lossless compression }
ifPsd,
{** Targa format (TGA), transparency, rudimentary lossless compression }
ifTarga,
{** TIFF format, limited support }
ifTiff,
{** X-Window capture, limited support }
ifXwd,
{** X-Pixmap, text encoded image, limited support }
ifXPixMap);
{* Image information from superficial analysis }
TQuickImageInfo = record
{** Width in pixels }
Width,
{** Height in pixels }
Height,
{** Bitdepth for colors (1, 2, 4, 8 for images with palette/grayscale, 16, 24 or 48 if each channel is present) }
ColorDepth,
{** Bitdepth for alpha (0 if no alpha channel, 1 if bit mask, 8 or 16 if alpha channel) }
AlphaDepth: Integer;
end;
TBGRAImageReader = class(TFPCustomImageReader)
function GetQuickInfo(AStream: TStream): TQuickImageInfo; virtual; abstract;
end;
{* Options when loading an image }
TBGRALoadingOption = (
{** Do not clear RGB channels when alpha is zero (not recommended) }
loKeepTransparentRGB,
{** Consider BMP to be opaque if no alpha value is provided (for compatibility) }
loBmpAutoOpaque,
{** Load JPEG quickly however with a lower quality }
loJpegQuick);
TBGRALoadingOptions = set of TBGRALoadingOption;
{$DEFINE INCLUDE_INTERFACE}
{$I bgracustombitmap.inc}
{==== Integer math ====}
{* Computes the value modulo cycle, and if the ''value'' is negative, the result
is still positive }
function PositiveMod(value, cycle: Int32or64): Int32or64; overload; {$ifdef inline}inline;{$endif}
{ Sin65536 and Cos65536 are fast routines to compute sine and cosine as Integer values.
They use a table to store already computed values. The return value is an Integer
ranging from 0 to 65536, so the mean value is 32768 and the half amplitude is
32768 instead of 1. The input has a period of 65536, so you can supply any Integer
without applying a modulo. }
{ Compute all values now }
procedure PrecalcSin65536;
{* Returns an Integer approximation of the sine. Value ranges from 0 to 65535,
where 65536 corresponds to the next cycle }
function Sin65536(value: BGRAWord): Int32or64; //@{$ifdef inline}inline;{$endif}
{* Returns an Integer approximation of the cosine. Value ranges from 0 to 65535,
where 65536 corresponds to the next cycle }
function Cos65536(value: BGRAWord): Int32or64; {$ifdef inline}inline;{$endif}
{* Returns the square root of the given byte, considering that
255 is equal to unity }
function ByteSqrt(value: byte): byte; //@{$ifdef inline}inline;{$endif}
/////////////////// {==== Integer math ====} /////////////////////////
{** Removes line ending and tab characters from a string (for a function
like ''TextOut'' that does not handle this). this works with UTF8 strings
as well }
function CleanTextOutString(s: string): string;
{** Remove the line ending at the specified position or return False.
This works with UTF8 strings however the index is the byte index }
function RemoveLineEnding(var s: string; indexByte: Integer): boolean;
{** Remove the line ending at the specified position or return False.
The index is the character index, that may be different from the
byte index }
function RemoveLineEndingUTF8(var sUTF8: string; indexUTF8: Integer): boolean;
{** Default BGRAWord break handler }
procedure BGRADefaultWordBreakHandler(var ABefore, AAfter: string);
{** Gives the sample filter represented by a string }
function StrToResampleFilter(str: string): TResampleFilter;
{** Detect the file format of a given file }
function DetectFileFormat(AFilenameUTF8: string): TBGRAImageFormat; overload;
{** Detect the file format of a given stream. ''ASuggestedExtensionUTF8'' can
be provided to guess the format }
function DetectFileFormat(AStream: TStream; ASuggestedExtensionUTF8: string = ''): TBGRAImageFormat; overload;
{** Returns the file format that is most likely to be stored in the
given filename (according to its extension) }
function SuggestImageFormat(AFilenameOrExtensionUTF8: string): TBGRAImageFormat;
{** Returns a likely image extension for the format }
function SuggestImageExtension(AFormat: TBGRAImageFormat): string;
{** Create an image reader for the given format }
function CreateBGRAImageReader(AFormat: TBGRAImageFormat): TFPCustomImageReader;
{** Create an image writer for the given format. ''AHasTransparentPixels''
specifies if alpha channel must be supported }
function CreateBGRAImageWriter(AFormat: TBGRAImageFormat; AHasTransparentPixels: boolean): TFPCustomImageWriter;
var
{** List of stream readers for images }
DefaultBGRAImageReader: array[TBGRAImageFormat] of TFPCustomImageReaderClass;
{** List of stream writers for images }
DefaultBGRAImageWriter: array[TBGRAImageFormat] of TFPCustomImageWriterClass;
const
{** List of strings to represent resample filters }
ResampleFilterStr : array[TResampleFilter] of string =
('Box','Linear','HalfCosine','Cosine','Bicubic','Mitchell','Spline',
'Lanczos2','Lanczos3','Lanczos4','BestQuality');
{$IFDEF BDS}
type
ArrayofBGRASingle = array of Single;
Arrayofword = array of BGRAWord;
procedure DynArrayToOpenArray(rOpen : array of TPointF; rDyn : array of TPointF);
function SliceDynArray(rOpen : array of TPointF; Count : integer): arrayofTPointF; overload;
function SliceDynArray(rOpen : array of TBGRAPixel; Count : integer): ArrayOfTBGRAPixel; overload;
function SliceDynArray(rOpen : array of Single; Count : Integer): ArrayofBGRASingle; overload;
function SliceDynArray(rOpen : array of BGRAWord; Count : Integer): Arrayofword; overload;
function SliceDynArray(rOpen : array of TColorF; Count : integer): arrayofTColorF; overload;
{$ENDIF}
implementation
uses Math, SysUtils, BGRAUTF8, BGRAUnicode,
FPReadXwd, FPReadXPM, FPWriteJPEG, FPWriteBMP, FPWriteXPM,
{$IFDEF FPC}
FPWriteTiff, FPWritePCX, FPWriteTGA,
{$ENDIF}
BGRAWritePNG;
{$IFDEF BDS}
function SliceDynArray(rOpen : array of TColorF; Count : integer): arrayofTColorF;
var
i : integer;
Open : arrayofTColorF;
begin
SetLength(Open, Length(rOpen));
for i := 0 to High(rOpen) do
Open[i] := rOpen[i];
Result := Copy(Open, 0, Count);
end;
function SliceDynArray(rOpen : array of TBGRAPixel; Count : integer): ArrayOfTBGRAPixel;
var
i : integer;
Open : ArrayOfTBGRAPixel;
begin
SetLength(Open, Length(rOpen));
for i := 0 to High(rOpen) do
Open[i] := rOpen[i];
Result := Copy(Open, 0, Count);
end;
procedure DynArrayToOpenArray(rOpen : array of TPointF; rDyn : array of TPointF);
var
i : integer;
begin
for i := 0 to High(rDyn) do
rOpen[i] := rDyn[i];
end;
function SliceDynArray(rOpen : array of TPointF; Count : integer): arrayofTPointF;
var
i : integer;
Open : arrayofTPointF;
begin
SetLength(Open, Length(rOpen));
for i := 0 to High(rOpen) do
Open[i] := rOpen[i];
Result := Copy(Open, 0, Count);
end;
function SliceDynArray(rOpen : array of Single; Count : Integer): ArrayofBGRASingle;
var
i : integer;
Open : ArrayofBGRASingle;
begin
SetLength(Open, Length(rOpen));
for i := 0 to High(rOpen) do
Open[i] := rOpen[i];
Result := Copy(Open, 0, Count);
end;
function SliceDynArray(rOpen : array of BGRAWord; Count : Integer): Arrayofword;
var
i : integer;
Open : Arrayofword;
begin
SetLength(Open, Length(rOpen));
for i := 0 to High(rOpen) do
Open[i] := rOpen[i];
Result := Copy(Open, 0, Count);
end;
{$ENDIF}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I geometrytypes.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I csscolorconst.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I bgracustombitmap.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I bgrapixel.inc}
function CleanTextOutString(s: string): string;
var idxIn, idxOut: integer;
begin
setlength(result, length(s));
idxIn := 1;
idxOut := 1;
while IdxIn <= length(s) do
begin
if not (s[idxIn] in[#13,#10,#9]) then //those characters are always 1 byte long so it is the same with UTF8
begin
result[idxOut] := s[idxIn];
inc(idxOut);
end;
inc(idxIn);
end;
setlength(result, idxOut-1);
end;
function RemoveLineEnding(var s: string; indexByte: integer): boolean;
begin //we can ignore UTF8 character length because #13 and #10 are always 1 byte long
//so this function can be applied to UTF8 strings as well
result := false;
if length(s) >= indexByte then
begin
if s[indexByte] in[#13,#10] then
begin
result := true;
if length(s) >= indexByte+1 then
begin
if (s[indexByte+1] <> s[indexByte]) and (s[indexByte+1] in[#13,#10]) then
delete(s,indexByte,2)
else
delete(s,indexByte,1);
end
else
delete(s,indexByte,1);
end;
end;
end;
function RemoveLineEndingUTF8(var sUTF8: string; indexUTF8: integer): boolean;
var indexByte: integer;
pIndex: PChar; //@{$IFDEF FPC}PChar{$ELSE}PAnsiChar{$ENDIF};
begin
pIndex := UTF8CharStart(@sUTF8[1],length(sUTF8),indexUTF8);
if pIndex = nil then
begin
result := false;
exit;
end;
indexByte := pIndex - @sUTF8[1];
result := RemoveLineEnding(sUTF8, indexByte);
end;
procedure BGRADefaultWordBreakHandler(var ABefore, AAfter: string);
const spacingChars = [' '];
wordBreakChars = [' ',#9,'-','?','!'];
var p, charLen: integer;
u: BGRACardinal;
begin
if (AAfter <> '') and (ABefore <> '') and not (AAfter[1] in spacingChars) and not (ABefore[length(ABefore)] in wordBreakChars) then
begin
p := length(ABefore);
while (p > 1) and not (ABefore[p-1] in wordBreakChars) do dec(p);
while (p < length(ABefore)+1) and (ABefore[p] in [#$80..#$BF]) do inc(p); //do not split UTF8 char
//keep non-spacing mark together
while p <= length(ABefore) do
begin
charLen := UTF8CharacterLength(@ABefore[p]);
if p+charLen > length(ABefore)+1 then charLen := length(ABefore)+1-p;
u := UTF8CodepointToUnicode(@ABefore[p],charLen);
if GetUnicodeBidiClass(u) = ubcNonSpacingMark then
inc(p,charLen)
else
break;
end;
if p = 1 then
begin
//keep ideographic punctuation together
charLen := UTF8CharacterLength(@AAfter[p]);
if charLen > length(AAfter) then charLen := length(AAfter);
u := UTF8CodepointToUnicode(@AAfter[p],charLen);
case u of
UNICODE_IDEOGRAPHIC_COMMA,
UNICODE_IDEOGRAPHIC_FULL_STOP,
UNICODE_FULLWIDTH_COMMA,
UNICODE_HORIZONTAL_ELLIPSIS:
begin
p := length(ABefore)+1;
while p > 1 do
begin
charLen := 1;
dec(p);
while (p > 0) and (ABefore[p] in [#$80..#$BF]) do
begin
dec(p); //do not split UTF8 char
inc(charLen);
end;
if charLen <= 4 then
u := UTF8CodepointToUnicode(@ABefore[p],charLen)
else
u := ord('A');
case GetUnicodeBidiClass(u) of
ubcNonSpacingMark: ; // include NSM
ubcOtherNeutrals, ubcWhiteSpace, ubcCommonSeparator, ubcEuropeanNumberSeparator:
begin
p := 1;
break;
end
else
break;
end;
end;
end;
end;
end;
if p > 1 then //can put the BGRAWord after
begin
AAfter := copy(ABefore,p,length(ABefore)-p+1)+AAfter;
ABefore := copy(ABefore,1,p-1);
end else
begin //cannot put the BGRAWord after, so before
end;
end;
while (ABefore <> '') and (ABefore[length(ABefore)] in spacingChars) do delete(ABefore,length(ABefore),1);
while (AAfter <> '') and (AAfter[1] in spacingChars) do delete(AAfter,1,1);
end;
function StrToResampleFilter(str: string): TResampleFilter;
var f: TResampleFilter;
begin
result := rfLinear;
str := LowerCase(str);
for f := low(TResampleFilter) to high(TResampleFilter) do
if CompareText(str,ResampleFilterStr[f])=0 then
begin
result := f;
exit;
end;
end;
{ TBGRACustomFontRenderer }
function TBGRACustomFontRenderer.TextSizeAngle(sUTF8: string;
orientationTenthDegCCW: integer): TSize;
begin
result := TextSize(sUTF8); //ignore orientation by default
end;
procedure TBGRACustomFontRenderer.TextOut(ADest: TBGRACustomBitmap; x,
y: single; sUTF8: string; c: TBGRAPixel; align: TAlignment;
ARightToLeft: boolean);
begin
//if RightToLeft is not handled
TextOut(ADest,x,y,sUTF8,c,align);
end;
procedure TBGRACustomFontRenderer.TextOut(ADest: TBGRACustomBitmap; x,
y: single; sUTF8: string; texture: IBGRAScanner; align: TAlignment;
ARightToLeft: boolean);
begin
//if RightToLeft is not handled
TextOut(ADest,x,y,sUTF8,texture,align);
end;
procedure TBGRACustomFontRenderer.CopyTextPathTo(ADest: IBGRAPath; x, y: single; s: string; align: TAlignment);
begin {optional implementation} end;
function CheckPutImageBounds(x, y, tx, ty: integer; out minxb, minyb, maxxb,
maxyb, ignoreleft: integer; const cliprect: TRect): boolean;
var x2,y2: integer;
begin
if (x >= cliprect.Right) or (y >= cliprect.Bottom) or (x <= cliprect.Left-tx) or
(y <= cliprect.Top-ty) or (ty <= 0) or (tx <= 0) then
begin
result := false;
exit;
end;
x2 := x + tx - 1;
y2 := y + ty - 1;
if y < cliprect.Top then
minyb := cliprect.Top
else
minyb := y;
if y2 >= cliprect.Bottom then
maxyb := cliprect.Bottom - 1
else
maxyb := y2;
if x < cliprect.Left then
begin
ignoreleft := cliprect.Left-x;
minxb := cliprect.Left;
end
else
begin
ignoreleft := 0;
minxb := x;
end;
if x2 >= cliprect.Right then
maxxb := cliprect.Right - 1
else
maxxb := x2;
result := true;
end;
{************************** Cyclic functions *******************}
// Get the cyclic value in the range [0..cycle-1]
function PositiveMod(value, cycle: Int32or64): Int32or64; {$ifdef inline}inline;{$endif}
begin
result := value mod cycle;
if result < 0 then //modulo can be negative
Inc(result, cycle);
end;
{ Table of precalc values. Note : the value is stored for
the first half of the cycle, and values are stored 'minus 1'
in order to stay in the range 0..65535 }
var
sinTab65536: TArrayWord;
byteSqrtTab: TArrayWord;
function Sin65536(value: BGRAWord): Int32or64;
var b: integer;
begin
//allocate array
if sinTab65536 = nil then
setlength(sinTab65536,32768);
if value >= 32768 then //function is upside down after half-period
begin
b := value xor 32768;
if sinTab65536[b] = 0 then //precalc
sinTab65536[b] := round((sin(b*2*Pi/65536)+1)*65536/2)-1;
result := not sinTab65536[b];
end else
begin
b := value;
if sinTab65536[b] = 0 then //precalc
sinTab65536[b] := round((sin(b*2*Pi/65536)+1)*65536/2)-1;
{$hints off}
result := sinTab65536[b]+1;
{$hints on}
end;
end;
function Cos65536(value: BGRAWord): Int32or64;
begin
{$IFDEF FPC}{$PUSH}{$ENDIF}{$R-}
result := Sin65536(value+16384); //cosine is translated
{$IFDEF FPC}{$POP}{$ENDIF}
end;
procedure PrecalcSin65536;
var
i: Integer;
begin
for i := 0 to 32767 do Sin65536(i);
end;
procedure PrecalcByteSqrt;
var i: integer;
begin
if byteSqrtTab = nil then
begin
setlength(byteSqrtTab,256);
for i := 0 to 255 do
byteSqrtTab[i] := round(sqrt(i/255)*255);
end;
end;
function ByteSqrt(value: byte): byte;
begin
if byteSqrtTab = nil then PrecalcByteSqrt;
result := ByteSqrtTab[value];
end;
function DetectFileFormat(AFilenameUTF8: string): TBGRAImageFormat;
var stream: TFileStreamUTF8;
begin
try
stream := TFileStreamUTF8.Create(AFilenameUTF8,fmOpenRead or fmShareDenyWrite);
except
result := ifUnknown;
exit;
end;
try
result := DetectFileFormat(stream, ExtractFileExt(AFilenameUTF8));
finally
stream.Free;
end;
end;
function DetectFileFormat(AStream: TStream; ASuggestedExtensionUTF8: string
): TBGRAImageFormat;
var
scores: array[TBGRAImageFormat] of integer;
imageFormat,bestImageFormat: TBGRAImageFormat;
bestScore: integer;
procedure DetectFromStream;
var
{%H-}magic: packed array[0..7] of byte;
{%H-}dwords: packed array[0..9] of BGRADWord;
magicAsText: string;
streamStartPos, maxFileSize: BGRAInt64;
expectedFileSize: BGRADWord;
procedure DetectTarga;
var
paletteCount: integer;
{%H-}targaPixelFormat: packed record pixelDepth: byte; imgDescriptor: byte; end;
begin
if (magic[1] in[$00,$01]) and (magic[2] in[0,1,2,3,9,10,11]) and (maxFileSize >= 18) then
begin
paletteCount:= magic[5] + magic[6] shl 8;
if ((paletteCount = 0) and (magic[7] = 0)) or
(magic[7] in [16,24,32]) then //check palette bit count
begin
AStream.Position:= streamStartPos+16;
if AStream.Read({%H-}targaPixelFormat,2) = 2 then
begin
if (targaPixelFormat.pixelDepth in [8,16,24,32]) and
(targaPixelFormat.imgDescriptor and 15 < targaPixelFormat.pixelDepth) then
inc(scores[ifTarga],2);
end;
end;
end;
end;
procedure DetectLazPaint;
var
w,h: BGRADWord;
i: integer;
begin
if (copy(magicAsText,1,8) = 'LazPaint') then //with header
begin
AStream.Position:= streamStartPos+8;
if AStream.Read(dwords,10*4) = 10*4 then
begin
for i := 0 to 6 do
{$IFNDEF BDS}dwords[i] := LEtoN(dwords[i]);{$ENDIF}
if (dwords[0] = 0) and (dwords[1] <= maxFileSize) and (dwords[5] <= maxFileSize) and
(dwords[9] <= maxFileSize) and
(dwords[6] = 0) then inc(scores[ifLazPaint],2);
end;
end else //without header
if ((magic[0] <> 0) or (magic[1] <> 0)) and (magic[2] = 0) and (magic[3] = 0) and
((magic[4] <> 0) or (magic[5] <> 0)) and (magic[6] = 0) and (magic[7] = 0) then
begin
w := magic[0] + (magic[1] shl 8);
h := magic[4] + (magic[5] shl 8);
AStream.Position:= streamStartPos+8;
if AStream.Read(dwords,4) = 4 then
begin
{$IFNDEF BDS}dwords[0] := LEtoN(dwords[0]){$ENDIF};
if (dwords[0] > 0) and (dwords[0] < 65536) then
begin
if 12+dwords[0] < expectedFileSize then
begin
AStream.Position:= streamStartPos+12+dwords[0];
if AStream.Read(dwords,6*4) = 6*4 then
begin
for i := 0 to 5 do {$IFNDEF BDS}dwords[i] := LEtoN(dwords[i]){$ENDIF};
if (dwords[0] <= w) and (dwords[1] <= h) and
(dwords[2] <= w) and (dwords[3] <= h) and
(dwords[2] >= dwords[0]) and (dwords[3] >= dwords[1]) and
((dwords[4] = 0) or (dwords[4] = 1)) and
(dwords[5] > 0) then inc(scores[ifLazPaint],1);
end;
end;
end;
end;
end;
end;
begin
fillchar({%H-}magic, sizeof(magic), 0);
fillchar({%H-}dwords, sizeof(dwords), 0);
streamStartPos:= AStream.Position;
maxFileSize:= AStream.Size - streamStartPos;
if maxFileSize < 8 then exit;