-
Notifications
You must be signed in to change notification settings - Fork 12
/
bgraiconcursor.pas
798 lines (721 loc) · 25.6 KB
/
bgraiconcursor.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
{ ***************************************************************************
* *
* 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 BGRAIconCursor;
{$i bgrabitmap.inc}{$H+}
interface
uses
Classes, SysUtils, {$IFNDEF FPC}Types, GraphType, BGRAGraphics,{$ENDIF}BGRATypes, BGRAMultiFileType, BGRABitmapTypes;
type
{ TBGRAIconCursorEntry }
TBGRAIconCursorEntry = class(TMultiFileEntry)
protected
FWidth,FHeight,FBitDepth: integer;
FExtension: string;
FContent: TStream;
FHotSpot: TPoint;
function GetName: utf8string; override;
procedure SetName({%H-}AValue: utf8string); override;
function GetExtension: utf8string; override;
function GetFileSize: BGRAInt64; override;
public
constructor Create(AContainer: TMultiFileContainer; AExtension: string; AInfo: TQuickImageInfo; AContent: TStream);
class function TryCreate(AContainer: TMultiFileContainer; AContent: TStream): TBGRAIconCursorEntry;
destructor Destroy; override;
function CopyTo(ADestination: TStream): BGRAInt64; override;
function GetBitmap: TBGRACustomBitmap;
property Width: integer read FWidth;
property Height: integer read FHeight;
property BitDepth: integer read FBitDepth;
property HotSpot: TPoint read FHotSpot write FHotSpot;
end;
{ TBGRAIconCursor }
TBGRAIconCursor = class(TMultiFileContainer)
private
function GetBitDepthAt(AIndex: integer): integer;
function GetHeightAt(AIndex: integer): integer;
function GetHotSpotAtAt(AIndex: integer): TPoint;
function GetWidthAt(AIndex: integer): integer;
procedure SetFileType(AValue: TBGRAImageFormat);
procedure SetHotSpotAt(AIndex: integer; AValue: TPoint);
protected
FFileType : TBGRAImageFormat;
FLoading : boolean;
function CreateEntry(AName: utf8string; AExtension: utf8string;
AContent: TStream): TMultiFileEntry; override;
function ExpectedMagic: BGRAWord;
procedure Init; override;
public
constructor Create(AFileType: TBGRAImageFormat); overload;
function Add(ABitmap: TBGRACustomBitmap; ABitDepth: integer; AOverwrite: boolean = false): integer; overload;
function Add(AContent: TStream; AOverwrite: boolean = false; AOwnStream: boolean = true): integer; overload;
procedure LoadFromStream(AStream: TStream); override;
procedure SaveToStream(ADestination: TStream); override;
function GetBitmap(AIndex: integer): TBGRACustomBitmap;
function GetBestFitBitmap(AWidth,AHeight: integer): TBGRACustomBitmap;
function IndexOf(AWidth,AHeight,ABitDepth: integer): integer; overload;
property FileType: TBGRAImageFormat read FFileType write SetFileType;
property Width[AIndex: integer]: integer read GetWidthAt;
property Height[AIndex: integer]: integer read GetHeightAt;
property BitDepth[AIndex: integer]: integer read GetBitDepthAt;
property HotSpot[AIndex: integer]: TPoint read GetHotSpotAtAt write SetHotSpotAt;
end;
function BGRADitherIconCursor(ABitmap: TBGRACustomBitmap; ABitDepth: integer; ADithering: TDitheringAlgorithm): TBGRACustomBitmap;
implementation
uses BGRAWinResource, BGRAUTF8, BGRAReadPng, BGRAReadBMP, FPWriteBMP, BGRAPalette, BGRAWritePNG,
BGRAColorQuantization;
function BGRADitherIconCursor(ABitmap: TBGRACustomBitmap; ABitDepth: integer;
ADithering: TDitheringAlgorithm): TBGRACustomBitmap;
var
frameMask, temp: TBGRACustomBitmap;
quantizer: TBGRAColorQuantizer;
maskQuantizer: TBGRAColorQuantizer;
x,y: integer;
psrc,pdest: PBGRAPixel;
begin
if ABitDepth <= 0 then
raise exception.Create('Invalid bit depth');
if ABitDepth <= 24 then
begin
if ABitDepth = 1 then
begin
quantizer := TBGRAColorQuantizer.Create([BGRABlack,BGRAWhite,BGRAPixelTransparent],false,3);
result := quantizer.GetDitheredBitmap(ADithering, ABitmap);
quantizer.Free;
end
else
begin
frameMask := ABitmap.GetMaskFromAlpha;
maskQuantizer := TBGRAColorQuantizer.Create([BGRABlack,BGRAWhite],false,2);
temp := maskQuantizer.GetDitheredBitmap(ADithering, frameMask);
frameMask.Free;
frameMask := temp;
maskQuantizer.Free;
result := ABitmap.Duplicate;
result.ReplaceTransparent(BGRABlack);
result.AlphaFill(255);
if ABitDepth <= 8 then
begin
quantizer := TBGRAColorQuantizer.Create(result,acFullChannelInPalette, 1 shl ABitDepth);
temp := quantizer.GetDitheredBitmap(daFloydSteinberg, result);
result.free;
result := temp;
quantizer.Free;
end;
result.ApplyMask(frameMask);
frameMask.Free;
end;
end else
result := ABitmap.Duplicate;
if Assigned(ABitmap.XorMask) then
begin
result.NeedXorMask;
for y := 0 to ABitmap.XorMask.Height-1 do
begin
psrc := ABitmap.XorMask.ScanLine[y];
pdest := result.XorMask.ScanLine[y];
for x := 0 to ABitmap.XorMask.Width-1 do
begin
if ((psrc^.red shl 1)+(psrc^.green shl 2)+psrc^.blue >= 128*(1+2+4)) then
pdest^ := BGRA(255,255,255,0);
inc(psrc);
inc(pdest);
end;
end;
end;
end;
{ TBGRAIconCursorEntry }
constructor TBGRAIconCursorEntry.Create(AContainer: TMultiFileContainer; AExtension: string; AInfo: TQuickImageInfo;
AContent: TStream);
begin
inherited Create(AContainer);
FExtension:= AExtension;
FWidth := AInfo.Width;
FHeight:= AInfo.Height;
// 16 bit per channel is not relevant for icon depth
if AInfo.ColorDepth >= 24 then
begin
if AInfo.AlphaDepth >= 8 then
FBitDepth := 32
else
FBitDepth := 24;
end else
FBitDepth := AInfo.ColorDepth;
FContent := AContent;
end;
class function TBGRAIconCursorEntry.TryCreate(
AContainer: TMultiFileContainer; AContent: TStream): TBGRAIconCursorEntry;
var
format: TBGRAImageFormat;
imageInfo: TQuickImageInfo;
tempStream: TMemoryStream;
reader: TBGRAImageReader;
bmp: TBGRACustomBitmap;
maskLine: packed array of byte;
maskStride: integer;
psrc: PBGRAPixel;
maskBit: byte;
maskPos,x,y: integer;
headerSize, dataSize: integer;
begin
AContent.Position:= 0;
format := DetectFileFormat(AContent);
case format of
ifBmp:
begin
reader := TBGRAReaderBMP.Create;
bmp := BGRABitmapFactory.Create;
try
AContent.Position := 0;
imageInfo := reader.GetQuickInfo(AContent);
if (imageInfo.width <= 0) or (imageInfo.height <= 0) or
(imageInfo.width > 256) or (imageInfo.height > 256) then
raise exception.Create('Invalid image size');
AContent.Position := 0;
//load bitmap to build mask
bmp.LoadFromStream(AContent);
maskStride := ((bmp.Width+31) div 32)*4;
tempStream := TMemoryStream.Create;
//BMP header is not stored in icon/cursor
AContent.Position:= sizeof(TBitMapFileHeader);
tempStream.CopyFrom(AContent, AContent.Size - sizeof(TBitMapFileHeader));
AContent.Free;
//fix height
tempStream.Position := 0;
headerSize := {$IFNDEF BDS}LEtoN{$ENDIF}(tempStream.ReadDWord);
if headerSize = sizeof(TOS2BitmapHeader) then // OS/2 1.x
begin
tempStream.Position := 6;
tempStream.WriteWord({$IFNDEF BDS}NtoLE{$ENDIF}(BGRAWord(bmp.Height*2))); //include mask size
end else
begin
tempStream.Position := 8;
tempStream.WriteDWord({$IFNDEF BDS}NtoLE{$ENDIF}(BGRADWord(bmp.Height*2))); //include mask size
if headerSize >= 20+4 then
begin
tempStream.Position:= 20;
dataSize := {$IFNDEF BDS}LEtoN{$ENDIF}(tempStream.ReadDWord);
if dataSize <> 0 then
begin //if data size is supplied, include mask size
dataSize := dataSize +(maskStride*bmp.Height);
tempStream.Position:= 20;
tempStream.WriteDWord({$IFNDEF BDS}NtoLE{$ENDIF}(dataSize));
end;
end;
end;
//build mask
tempStream.Position := tempStream.Size;
setlength(maskLine, maskStride);
for y := bmp.Height-1 downto 0 do
begin
maskBit := $80;
maskPos := 0;
psrc := bmp.ScanLine[y];
fillchar(maskLine[0], length(maskLine), 0);
for x := 0 to bmp.Width-1 do
begin
if psrc^.alpha = 0 then
maskLine[maskPos] := maskLine[maskPos] or maskBit;
maskBit := maskBit shr 1;
if maskBit = 0 then
begin
maskBit := $80;
maskPos := maskPos +1;
end;
inc(psrc);
end;
tempStream.WriteBuffer(maskLine[0], length(maskLine));
end;
result := TBGRAIconCursorEntry.Create(AContainer, 'dib', imageInfo, tempStream);
finally
bmp.Free;
reader.Free;
end;
end;
ifPng:
begin
reader := TBGRAReaderPNG.Create;
imageInfo := reader.GetQuickInfo(AContent);
reader.Free;
result := TBGRAIconCursorEntry.Create(AContainer, 'png', imageInfo, AContent);
end;
ifUnknown, ifLazPaint {a headerless bmp can be confused for a headerless lzp}:
begin
//assume headerless BMP
AContent.Position := 0;
reader := TBGRAReaderBMP.Create;
imageInfo := reader.GetQuickInfo(AContent);
imageInfo.Height:= imageInfo.Height div 2; //mask size is included
reader.Free;
if (imageInfo.width <= 0) or (imageInfo.height <= 0) or
(imageInfo.width > 256) or (imageInfo.height > 256) then
raise exception.Create('Invalid image size');
result := TBGRAIconCursorEntry.Create(AContainer, 'dib', imageInfo, AContent);
end;
else
raise exception.Create(SuggestImageExtension(format) + ' format is not handled');
end;
end;
destructor TBGRAIconCursorEntry.Destroy;
begin
FContent.Free;
inherited Destroy;
end;
function TBGRAIconCursorEntry.CopyTo(ADestination: TStream): BGRAInt64;
begin
if FContent.Size = 0 then
begin
result := 0;
exit;
end;
FContent.Position := 0;
result := ADestination.CopyFrom(FContent, FContent.Size);
end;
function TBGRAIconCursorEntry.GetBitmap: TBGRACustomBitmap;
var reader: TBGRAImageReader;
begin
if Extension = 'dib' then
begin
reader := TBGRAReaderBMP.Create;
TBGRAReaderBMP(reader).Subformat := bsfHeaderlessWithMask;
end else
reader := TBGRAReaderPNG.create;
result := BGRABitmapFactory.Create;
FContent.Position := 0;
try
result.LoadFromStream(FContent, reader);
except on ex: Exception do
begin
result.Free;
reader.Free;
raise ex;
end;
end;
reader.Free;
result.HotSpot := HotSpot;
end;
function TBGRAIconCursorEntry.GetName: utf8string;
begin
result := IntToStr(FWidth)+'x'+IntToStr(FHeight)+'x'+IntToStr(FBitDepth);
end;
procedure TBGRAIconCursorEntry.SetName(AValue: utf8string);
begin
raise exception.Create('Name cannot be changed');
end;
function TBGRAIconCursorEntry.GetExtension: utf8string;
begin
result := FExtension;
end;
function TBGRAIconCursorEntry.GetFileSize: BGRAInt64;
begin
result := FContent.Size;
end;
{ TBGRAIconCursor }
function TBGRAIconCursor.GetBitDepthAt(AIndex: integer): integer;
begin
if (AIndex < 0) or (AIndex >= Count) then raise ERangeError.Create('Index out of bounds');
result := TBGRAIconCursorEntry(Entry[AIndex]).BitDepth;
end;
function TBGRAIconCursor.GetHeightAt(AIndex: integer): integer;
begin
if (AIndex < 0) or (AIndex >= Count) then raise ERangeError.Create('Index out of bounds');
result := TBGRAIconCursorEntry(Entry[AIndex]).Height;
end;
function TBGRAIconCursor.GetHotSpotAtAt(AIndex: integer): TPoint;
begin
if (AIndex < 0) or (AIndex >= Count) then raise ERangeError.Create('Index out of bounds');
result := TBGRAIconCursorEntry(Entry[AIndex]).HotSpot;
end;
function TBGRAIconCursor.GetWidthAt(AIndex: integer): integer;
begin
if (AIndex < 0) or (AIndex >= Count) then raise ERangeError.Create('Index out of bounds');
result := TBGRAIconCursorEntry(Entry[AIndex]).Width;
end;
procedure TBGRAIconCursor.SetFileType(AValue: TBGRAImageFormat);
begin
if FFileType=AValue then Exit;
if not (AValue in [ifIco,ifCur,ifUnknown]) then
raise exception.Create('Allowed formats: ICO, CUR or unknown');
FFileType:=AValue;
end;
procedure TBGRAIconCursor.SetHotSpotAt(AIndex: integer; AValue: TPoint);
begin
if (AIndex < 0) or (AIndex >= Count) then raise ERangeError.Create('Index out of bounds');
TBGRAIconCursorEntry(Entry[AIndex]).HotSpot := AValue;
end;
function TBGRAIconCursor.CreateEntry(AName: utf8string;
AExtension: utf8string; AContent: TStream): TMultiFileEntry;
begin
AExtension := UTF8LowerCase(AExtension);
if (AExtension <> 'png') and (AExtension <> 'dib') then
raise exception.Create('The only supported extensions are PNG and DIB');
result := TBGRAIconCursorEntry.TryCreate(self, AContent);
if result.Extension <> AExtension then
begin
result.Free;
raise exception.Create(AExtension + ' file extension expected but ' + result.Extension + ' found');
end;
if result.Name <> AName then
begin
result.Free;
raise exception.Create('"' + AName + '" dimension expected but "' + result.Name + '" found');
end;
end;
function TBGRAIconCursor.ExpectedMagic: BGRAWord;
begin
case FFileType of
ifIco: result := ICON_OR_CURSOR_FILE_ICON_TYPE;
ifCur: result := ICON_OR_CURSOR_FILE_CURSOR_TYPE;
else
raise exception.Create('Invalid icon/cursor type');
end;
end;
procedure TBGRAIconCursor.Init;
begin
inherited Init;
FFileType:= ifUnknown;
end;
constructor TBGRAIconCursor.Create(AFileType: TBGRAImageFormat);
begin
if not (AFileType in [ifIco,ifCur,ifUnknown]) then
raise exception.Create('Allowed formats: ICO, CUR or unknown');
Init;
FFileType := AFileType;
end;
function TBGRAIconCursor.Add(ABitmap: TBGRACustomBitmap; ABitDepth: integer;
AOverwrite: boolean): integer;
var stream, temp: TStream;
writer: TFPWriterBMP;
bmpXOR: TBGRACustomBitmap;
y: Integer;
psrcMask, pdest: PBGRAPixel;
bitAndMask: array of byte;
bitAndMaskPos: integer;
bitAndMaskBit: byte;
bitAndMaskRowSize, x: integer;
palette: TBGRAPalette;
writerPng: TBGRAWriterPNG;
begin
stream := TMemoryStream.Create;
try
//PNG format is advised from 256 on but does not handle XOR
if ((ABitmap.Width >= 256) or (ABitmap.Height >= 256)) and (ABitDepth >= 8) and
((ABitmap.XorMask = nil) or ABitmap.XorMask.IsZero) then
begin
writerPng := TBGRAWriterPNG.Create;
try
writerPng.WordSized := false;
if ABitDepth = 8 then
begin
writerPng.Indexed := true;
writerpng.UseAlpha := ABitmap.HasTransparentPixels;
end else
begin
writerPng.Indexed := false;
writerpng.UseAlpha := (ABitDepth = 32);
end;
ABitmap.SaveToStream(stream, writerPng);
finally
writerPng.Free;
end;
result := Add(stream, AOverwrite, true);
stream := nil;
end else
if ((ABitmap.XorMask = nil) or ABitmap.XorMask.IsZero) and
(not ABitmap.HasTransparentPixels or (ABitDepth = 32)) then
begin
writer := TFPWriterBMP.Create;
writer.BitsPerPixel := ABitDepth;
try
if not ABitmap.UsePalette and (ABitDepth < 24) then
begin
palette := TBGRAPalette.Create(ABitmap);
try
palette.AssignTo(ABitmap);
finally
palette.Free;
end;
ABitmap.SaveToStream(stream, writer);
ABitmap.UsePalette:= false;
end
else
ABitmap.SaveToStream(stream, writer);
finally
writer.Free;
end;
result := Add(stream, AOverwrite, true);
stream := nil;
end else
begin
bmpXOR := BGRABitmapFactory.Create(ABitmap);
try
bitAndMaskRowSize := ((bmpXOR.Width+31) div 32)*4;
setlength(bitAndMask, bitAndMaskRowSize*bmpXOR.Height);
for y := bmpXOR.Height-1 downto 0 do
begin
if assigned(ABitmap.XorMask) then
psrcMask := ABitmap.XorMask.ScanLine[y]
else
psrcMask := nil;
pdest := bmpXOR.ScanLine[y];
bitAndMaskPos := (bmpXOR.Height-1-y)*bitAndMaskRowSize;
bitAndMaskBit:= $80;
for x := bmpXOR.Width-1 downto 0 do
begin
//xor mask is either 100% or 0%
if assigned(psrcMask) and ((psrcMask^.red <> 0) or (psrcMask^.green <> 0) or (psrcMask^.blue <> 0)) then
begin
pdest^ := psrcMask^;
pdest^.alpha := 255;
bitAndMask[bitAndMaskPos] := bitAndMask[bitAndMaskPos] or bitAndMaskBit;
end else
if pdest^.alpha = 0 then
begin
bitAndMask[bitAndMaskPos] := bitAndMask[bitAndMaskPos] or bitAndMaskBit;
if ABitDepth <= 24 then //if we cannot save alpha, replace with black.
begin //mask will task care of making it transparent
pdest^ := BGRABlack;
end;
end;
bitAndMaskBit := bitAndMaskBit shr 1;
if bitAndMaskBit = 0 then
begin
bitAndMaskBit := $80;
bitAndMaskPos := bitAndMaskPos +1;
end;
if assigned(psrcMask) then inc(psrcMask);
inc(pdest);
end;
end;
bmpXOR.InvalidateBitmap;
if ABitDepth < 24 then
begin
palette := TBGRAPalette.Create(bmpXor);
palette.AssignTo(bmpXor);
palette.Free;
end;
temp := TMemoryStream.Create;
try
writer := TFPWriterBMP.Create;
writer.BitsPerPixel := ABitDepth;
try
bmpXOR.SaveToStream(temp, writer);
//write double height to include mask
temp.Position := 22;
temp.WriteDWord({$IFNDEF BDS}NtoLE{$ENDIF}(BGRADWord(bmpXOR.Height*2)));
//go after the file header
temp.Position := 14;
//copy bitmap without header
stream.CopyFrom(temp, temp.Size-temp.Position);
finally
writer.Free;
end;
finally
temp.Free;
end;
//write mask
stream.WriteBuffer(bitAndMask[0],length(bitAndMask));
result := Add(stream, AOverwrite, true);
stream := nil;
finally
bmpXOR.Free;
end;
end;
finally
stream.Free;
end;
end;
function TBGRAIconCursor.Add(AContent: TStream; AOverwrite: boolean;
AOwnStream: boolean): integer;
var
index,i: Integer;
newEntry: TBGRAIconCursorEntry;
contentCopy: TMemoryStream;
begin
if not AOwnStream then
begin
AContent.Position:= 0;
contentCopy := TMemoryStream.Create;
contentCopy.CopyFrom(AContent, AContent.Size);
newEntry := TBGRAIconCursorEntry.TryCreate(self, contentCopy);
end else
newEntry := TBGRAIconCursorEntry.TryCreate(self, AContent);
index := IndexOf(newEntry.Name, newEntry.Extension);
if index <> -1 then
begin
if AOverwrite then
Delete(index)
else
begin
newEntry.Free;
raise Exception.Create('Duplicate entry');
end;
end else if not FLoading then
begin
for i := 0 to Count-1 do
if ((Width[i] < newEntry.Width) and (Height[i] < newEntry.Height)) or
((Width[i] = newEntry.Width) and (Height[i] = newEntry.Height) and (BitDepth[i] < newEntry.BitDepth)) then
begin
index := i;
break;
end;
end;
result := AddEntry(newEntry, index);
end;
procedure TBGRAIconCursor.LoadFromStream(AStream: TStream);
var header: TGroupIconHeader;
dir: packed array of TIconFileDirEntry;
startPos: BGRAInt64;
entryContent: TMemoryStream;
entryIndex, i: integer;
begin
FLoading:= true;
try
startPos := AStream.Position;
AStream.ReadBuffer({%H-}header, sizeof(header));
header.SwapIfNecessary;
if header.Reserved <> 0 then
raise exception.Create('Invalid file format');
if FileType = ifUnknown then
begin
case header.ResourceType of
ICON_OR_CURSOR_FILE_ICON_TYPE: FFileType := ifIco;
ICON_OR_CURSOR_FILE_CURSOR_TYPE: FFileType := ifCur;
end;
end;
if header.ResourceType <> ExpectedMagic then
raise exception.Create('Invalid resource type');
Clear;
setlength(dir, header.ImageCount);
AStream.ReadBuffer(dir[0], sizeof(TIconFileDirEntry)*length(dir));
for i := 0 to high(dir) do
begin
AStream.Position:= {$IFNDEF BDS}LEtoN{$ENDIF}(dir[i].ImageOffset) + startPos;
entryContent := TMemoryStream.Create;
entryContent.CopyFrom(AStream, {$IFNDEF BDS}LEtoN{$ENDIF}(dir[i].ImageSize));
entryIndex := Add(entryContent, false, true);
if ((dir[i].Width = 0) and (Width[entryIndex] < 256)) or
((dir[i].Width > 0) and (Width[entryIndex] <> dir[i].Width)) or
((dir[i].Height = 0) and (Height[entryIndex] < 256)) or
((dir[i].Height > 0) and (Height[entryIndex] <> dir[i].Height)) then
raise Exception.Create('Inconsistent image size');
if FFileType = ifCur then
TBGRAIconCursorEntry(Entry[entryIndex]).HotSpot := Point({$IFNDEF BDS}LEtoN{$ENDIF}(dir[i].HotSpotX),{$IFNDEF BDS}LEtoN{$ENDIF}(dir[i].HotSpotY));
end;
finally
FLoading:= false;
end;
end;
procedure TBGRAIconCursor.SaveToStream(ADestination: TStream);
var header: TGroupIconHeader;
i: integer;
accSize: BGRADWord;
dir: packed array of TIconFileDirEntry;
contentSize: BGRADWord;
begin
if Count = 0 then
raise exception.Create('File cannot be empty');
if FileType = ifUnknown then
raise exception.Create('You need to specify the file type');
header.ImageCount:= Count;
header.Reserved := 0;
header.ResourceType:= ExpectedMagic;
header.SwapIfNecessary;
accSize := sizeof(header) + sizeof(TIconFileDirEntry)*Count;
setlength(dir, Count);
for i := 0 to Count-1 do
begin
if Width[i] >= 256
then dir[i].Width := 0
else dir[i].Width := Width[i];
if Height[i] >= 256
then dir[i].Height := 0
else dir[i].Height := Height[i];
if BitDepth[i] < 8 then
dir[i].Colors := 1 shl BitDepth[i]
else
dir[i].Colors := 0;
dir[i].Reserved := 0;
case FFileType of
ifCur: begin dir[i].HotSpotX:= {$IFNDEF BDS}NtoLE{$ENDIF}(BGRAWord(HotSpot[i].X)); dir[i].HotSpotY := {$IFNDEF BDS}NtoLE{$ENDIF}(BGRAWord(HotSpot[i].Y)); end;
ifIco: begin dir[i].BitsPerPixel:= {$IFNDEF BDS}NtoLE{$ENDIF}(BGRAWord(BitDepth[i])); dir[i].Planes := {$IFNDEF BDS}NtoLE{$ENDIF}(BGRAWord(1)); end;
else dir[i].Variable:= 0;
end;
dir[i].ImageOffset := {$IFNDEF BDS}LEtoN{$ENDIF}(accSize);
contentSize:= Entry[i].FileSize;
dir[i].ImageSize := {$IFNDEF BDS}NtoLE{$ENDIF}(contentSize);
inc(accSize,contentSize);
end;
ADestination.WriteBuffer(header, sizeof(header));
ADestination.WriteBuffer(dir[0], sizeof(TIconFileDirEntry)*length(dir));
for i := 0 to Count-1 do
if Entry[i].CopyTo(ADestination) <> Entry[i].FileSize then
raise exception.Create('Unable to write data in stream');
end;
function TBGRAIconCursor.GetBitmap(AIndex: integer): TBGRACustomBitmap;
begin
if (AIndex < 0) or (AIndex >= Count) then raise ERangeError.Create('Index out of bounds');
result := TBGRAIconCursorEntry(Entry[AIndex]).GetBitmap;
end;
function TBGRAIconCursor.GetBestFitBitmap(AWidth, AHeight: integer): TBGRACustomBitmap;
var bestIndex: integer;
bestSizeDiff: integer;
bestBPP: integer;
sizeDiff, i: integer;
begin
bestBPP := 0;
bestSizeDiff := high(integer);
bestIndex := -1;
for i := 0 to Count-1 do
begin
sizeDiff := abs(AWidth-Width[i])+abs(AHeight-Height[i]);
if (sizeDiff < bestSizeDiff) or
((sizeDiff = bestSizeDiff) and (BitDepth[i] > bestBPP)) then
begin
bestIndex := i;
bestSizeDiff:= sizeDiff;
bestBPP:= BitDepth[i];
end;
end;
if bestIndex = -1 then
raise Exception.Create('No bitmap found')
else
result := GetBitmap(bestIndex);
end;
function TBGRAIconCursor.IndexOf(AWidth, AHeight, ABitDepth: integer): integer;
var
i: Integer;
begin
for i := 0 to Count-1 do
if (Width[i] = AWidth) and (Height[i] = AHeight) and (BitDepth[i] = ABitDepth) then
begin
result := i;
exit;
end;
result := -1;
end;
end.