forked from edivando-fpc/BGRABitmap
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbgrapaintnet.pas
693 lines (626 loc) · 19.6 KB
/
bgrapaintnet.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
{ ***************************************************************************
* *
* 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 | mailedivando@gmail.com
(Compatibility with FPC ($Mode objfpc/delphi) and delphi VCL 11/2018)
***************************** END CONTRIBUTOR(S) *****************************}
Unit BGRAPaintNet;
{$i bgrabitmap.inc}{$H+}
interface
{ This unit reads Paint.NET files. It needs BGRADNetDeserial to deserialize binary .Net objects.
A Paint.NET image consists in three parts :
- Xml header
- Binary serialized information (contains layer information)
- Compressed data (pixel data)
The class TPaintDotNetFile do not read the Xml header. ComputeFlatImage builds the resulting image
by using blending operations to merge layers.
The unit registers a TFPCustomImageReader so that it can be read by any image reading function of FreePascal,
and also registers a reader for BGRALayers }
uses
Classes, SysUtils, BGRATypes,{$IFNDEF FPC}Types, GraphType, BGRAGraphics,{$ENDIF} BGRADNetDeserial, FPImage, BGRABitmapTypes, BGRABitmap, BGRALayers;
type
{ TPaintDotNetFile }
TPaintDotNetFile = class(TBGRACustomLayeredBitmap)
public
procedure LoadFromFile(const filenameUTF8: string); override;
procedure LoadFromStream(stream: TStream); override;
procedure Clear; override;
function ToString: ansistring; override;
function GetLayerBitmapCopy(layer: integer): TBGRABitmap; override;
constructor Create; override;
protected
procedure InternalLoadFromStream(stream: TStream);
function GetWidth: integer; override;
function GetHeight: integer; override;
function GetNbLayers: integer; override;
function GetBlendOperation(Layer: integer): TBlendOperation; override;
function GetLayerVisible(layer: integer): boolean; override;
function GetLayerOpacity(layer: integer): byte; override;
function GetLayerName(layer: integer): string; override;
private
Content: TDotNetDeserialization;
Document: TSerializedClass;
Layers: TSerializedClass;
LayerData: array of TMemoryStream;
function InternalGetLayer(num: integer): TSerializedClass;
function InternalGetBlendOperation(layer: TSerializedClass): TBlendOperation;
function InternalGetLayerName(layer: TSerializedClass): string;
function InternalGetLayerVisible(layer: TSerializedClass): boolean;
function InternalGetLayerOpacity(layer: TSerializedClass): byte;
function LayerDataSize(numLayer: integer): BGRAInt64;
procedure LoadLayer(dest: TMemoryStream; src: TStream; uncompressedSize: BGRAInt64);
end;
{ TFPReaderPaintDotNet }
TFPReaderPaintDotNet = class(TFPCustomImageReader)
private
FWidth,FHeight,FNbLayers: integer;
protected
function InternalCheck(Stream: TStream): boolean; override;
procedure InternalRead(Stream: TStream; Img: TFPCustomImage); override;
public
property Width: integer read FWidth;
property Height: integer read FHeight;
property NbLayers: integer read FNbLayers;
end;
function IsPaintDotNetFile(filename: string): boolean;
function IsPaintDotNetFileUTF8(filenameUTF8: string): boolean;
function IsPaintDotNetStream(stream: TStream): boolean;
function LoadPaintDotNetFile(filename: string): TBGRABitmap;
function LoadPaintDotNetFileUTF8(filenameUTF8: string): TBGRABitmap;
procedure RegisterPaintNetFormat;
implementation
uses zstream, Math, BGRAUTF8;
{$hints off}
function BEReadLongword(Stream: TStream): BGRALongWord;
begin
Stream.Read(Result, sizeof(Result));
Result := BEtoN(Result);
end;
{$hints on}
{$hints off}
function BEReadLongint(Stream: TStream): BGRALongInt;
begin
Stream.Read(Result, sizeof(Result));
Result := BEtoN(Result);
end;
function IsPaintDotNetFile(filename: string): boolean;
var
stream: TFileStream;
begin
Result := False;
if FileExists(filename) then
begin
stream := TFileStream.Create(filename, fmOpenRead);
Result := IsPaintDotNetStream(stream);
stream.Free;
end;
end;
function IsPaintDotNetFileUTF8(filenameUTF8: string): boolean;
var
stream: TFileStreamUTF8;
begin
Result := False;
if FileExistsUTF8(filenameUTF8) then
begin
stream := TFileStreamUTF8.Create(filenameUTF8, fmOpenRead);
Result := IsPaintDotNetStream(stream);
stream.Free;
end;
end;
function IsPaintDotNetStream(stream: TStream): boolean;
var
header: packed array[0..3] of {$IFDEF FPC}Char{$ELSE}AnsiChar{$ENDIF};
SavePos: BGRAInt64;
begin
Result := False;
try
if stream.Position + 4 < Stream.Size then
begin
header := #0#0#0#0;
SavePos := stream.Position;
stream.Read(header, 4);
stream.Position := SavePos;
if (header[0] = 'P') and (header[1] = 'D') and (header[2] = 'N') and
(header[3] = '3') then
Result := True;
end;
except
on ex: Exception do ;
end;
end;
function LoadPaintDotNetFile(filename: string): TBGRABitmap;
begin
result := LoadPaintDotNetFileUTF8(SysToUTF8(filename));
end;
function LoadPaintDotNetFileUTF8(filenameUTF8: string): TBGRABitmap;
var
pdn: TPaintDotNetFile;
begin
pdn := TPaintDotNetFile.Create;
Result := nil;
try
pdn.LoadFromFile(filenameUTF8);
Result := pdn.ComputeFlatImage;
pdn.Free;
except
on ex: Exception do
begin
FreeAndNil(Result);
pdn.Free;
raise Exception.Create('Error while loading Paint.NET file. ' + ex.Message);
end;
end;
end;
function LoadPaintDotNetStream(stream: TStream): TBGRABitmap;
var
pdn: TPaintDotNetFile;
begin
pdn := TPaintDotNetFile.Create;
Result := nil;
try
pdn.LoadFromStream(stream);
Result := pdn.ComputeFlatImage;
pdn.Free;
except
on ex: Exception do
begin
FreeAndNil(Result);
pdn.Free;
raise Exception.Create('Error while loading Paint.NET stream. ' + ex.Message);
end;
end;
end;
{$hints on}
{ TFPReaderPaintDotNet }
function TFPReaderPaintDotNet.InternalCheck(Stream: TStream): boolean;
begin
result := IsPaintDotNetStream(stream);
end;
procedure TFPReaderPaintDotNet.InternalRead(Stream: TStream; Img: TFPCustomImage);
var
pdn: TPaintDotNetFile;
flat: TBGRABitmap;
x,y: integer;
begin
FWidth := 0;
FHeight:= 0;
FNbLayers:= 0;
pdn := TPaintDotNetFile.Create;
try
pdn.LoadFromStream(Stream);
flat := pdn.ComputeFlatImage;
try
FWidth:= pdn.Width;
FHeight:= pdn.Height;
FNbLayers:= pdn.NbLayers;
if Img is TBGRACustomBitmap then
TBGRACustomBitmap(Img).Assign(flat) else
begin
Img.SetSize(pdn.Width,pdn.Height);
for y := 0 to pdn.Height-1 do
for x := 0 to pdn.Width-1 do
Img.Colors[x,y] := BGRAToFPColor(flat.GetPixel(x,y));
end;
finally
flat.free;
end;
pdn.Free;
except
on ex: Exception do
begin
pdn.Free;
raise Exception.Create('Error while loading Paint.NET file. ' + ex.Message);
end;
end;
end;
{ TPaintDotNetFile }
procedure TPaintDotNetFile.LoadFromFile(const filenameUTF8: string);
var
stream: TFileStreamUTF8;
begin
stream := TFileStreamUTF8.Create(filenameUTF8, fmOpenRead);
OnLayeredBitmapLoadStart(filenameUTF8);
try
InternalLoadFromStream(stream);
finally
OnLayeredBitmapLoaded;
stream.Free;
end;
end;
procedure TPaintDotNetFile.LoadFromStream(stream: TStream);
begin
OnLayeredBitmapLoadFromStreamStart;
try
InternalLoadFromStream(stream);
finally
OnLayeredBitmapLoaded;
end;
end;
procedure TPaintDotNetFile.InternalLoadFromStream(stream: TStream);
var
header: packed array[0..3] of {$IFDEF FPC}Char{$ELSE}AnsiChar{$ENDIF};
XmlHeaderSize: integer;
CompressionFormat: BGRAWord;
i: integer;
begin
Clear;
header := #0#0#0#0;
stream.Read(header, 4);
if (header[0] <> 'P') or (header[1] <> 'D') or (header[2] <> 'N') or
(header[3] <> '3') then
raise Exception.Create('Invalid header');
XmlHeaderSize := 0;
stream.Read(XmlHeaderSize, 3);
{$IFNDEF BDS}XmlheaderSize := LEtoN(XmlheaderSize);{$ENDIF}
if Stream.Position + XmlHeaderSize > stream.Size then
raise Exception.Create('Xml header size error');
Stream.Position:= Stream.Position + XmlHeaderSize;
{$hints off}
stream.ReadBuffer(CompressionFormat, sizeof(CompressionFormat));
{$hints on}
{$IFNDEF BDS}CompressionFormat := LEtoN(CompressionFormat);{$ENDIF}
Content := TDotNetDeserialization.Create;
case Compressionformat of
$0100: Content.LoadFromStream(Stream);
$8b1f: raise Exception.Create('Serialized data decompression not handled');
else
raise Exception.Create('Unknown compression format (' +
IntToStr(Compressionformat) + ')');
end;
Document := Content.FindClass('Document');
if Document <> nil then
Layers := Content.GetObjectField(Document, 'layers') as TSerializedClass;
SetLength(LayerData, NbLayers);
for i := 0 to NbLayers - 1 do
begin
OnLayeredBitmapLoadProgress((i+1)*100 div NbLayers);
LayerData[i] := TMemoryStream.Create;
LoadLayer(LayerData[i], Stream, LayerDataSize(i));
end;
end;
function TPaintDotNetFile.ToString: ansistring;
var
i, j, nbbytes: integer;
b: byte;
begin
Result := 'Paint.Net document' + LineEnding + LineEnding;
Result := Result +Content.ToString;
for i := 0 to NbLayers - 1 do
begin
Result := Result +LineEnding + 'Layer ' + IntToStr(i) + ' : ' + LayerName[i] + LineEnding;
Result := Result +'[ ';
LayerData[i].Position := 0;
if LayerData[i].Size > 256 then
nbbytes := 256
else
nbbytes := LayerData[i].Size;
for j := 0 to nbbytes - 1 do
begin
{$hints off}
LayerData[i].ReadBuffer(b, 1);
{$hints on}
Result := Result +IntToHex(b, 2) + ' ';
end;
if LayerData[i].Size > nbbytes then
Result := Result +'...';
Result := Result +']' + lineending;
end;
end;
constructor TPaintDotNetFile.Create;
begin
inherited Create;
Content := nil;
Document := nil;
Layers := nil;
LinearBlend := True;
RegisterPaintNetFormat;
end;
procedure TPaintDotNetFile.Clear;
var
i: integer;
begin
FreeAndNil(content);
document := nil;
Layers := nil;
for i := 0 to high(LayerData) do
LayerData[i].Free;
setLength(LayerData, 0);
end;
function TPaintDotNetFile.GetWidth: integer;
begin
if Document = nil then
Result := 0
else
Result := StrToInt(Content.GetSimpleField(Document, 'width'));
end;
function TPaintDotNetFile.GetHeight: integer;
begin
if Document = nil then
Result := 0
else
Result := StrToInt(Content.GetSimpleField(Document, 'height'));
end;
function TPaintDotNetFile.GetNbLayers: integer;
begin
if Layers = nil then
Result := 0
else
Result := StrToInt(Content.GetSimpleField(Layers, '_size'));
end;
function TPaintDotNetFile.GetBlendOperation(Layer: integer): TBlendOperation;
begin
Result := InternalGetBlendOperation(InternalGetLayer(layer));
end;
function TPaintDotNetFile.GetLayerVisible(layer: integer): boolean;
begin
Result := InternalGetLayerVisible(InternalGetLayer(layer));
end;
function TPaintDotNetFile.GetLayerOpacity(layer: integer): byte;
begin
Result := InternalGetLayerOpacity(InternalGetLayer(layer));
end;
function TPaintDotNetFile.GetLayerName(layer: integer): string;
begin
Result := InternalGetLayerName(InternalGetLayer(layer));
end;
function TPaintDotNetFile.GetLayerBitmapCopy(layer: integer): TBGRABitmap;
begin
if (layer < 0) or (layer >= NbLayers) then
raise Exception.Create('Index out of bounds');
Result := TBGRABitmap.Create(Width, Height);
if BGRAInt64(Result.NbPixels) * 4 <> LayerData[layer].Size then
begin
Result.Free;
raise Exception.Create('Inconsistent layer data size');
end
else
begin
layerData[layer].Position := 0;
layerData[layer].Read(Result.Data^, LayerData[layer].Size);
if TBGRAPixel_RGBAOrder then result.SwapRedBlue;
Result.InvalidateBitmap;
if Result.LineOrder = riloBottomToTop then
Result.VerticalFlip;
end;
end;
function TPaintDotNetFile.InternalGetLayerName(layer: TSerializedClass): string;
var
prop: TCustomSerializedObject;
begin
if layer = nil then
Result := ''
else
begin
prop := Content.GetObjectField(layer, 'Layer+properties');
if prop = nil then
Result := ''
else
begin
Result := Content.GetSimpleField(prop, 'name');
end;
end;
end;
function TPaintDotNetFile.LayerDataSize(numLayer: integer): BGRAInt64;
var
layer, surface, scan0: TCustomSerializedObject;
begin
layer := InternalGetLayer(numLayer);
if layer = nil then
Result := 0
else
begin
surface := Content.GetObjectField(layer, 'surface');
if surface = nil then
Result := 0
else
begin
scan0 := Content.GetObjectField(surface, 'scan0');
Result := StrToInt64(Content.GetSimpleField(scan0, 'length64'));
end;
end;
end;
procedure TPaintDotNetFile.LoadLayer(dest: TMemoryStream; src: TStream;
uncompressedSize: BGRAInt64);
var
CompressionFlag: byte;
maxChunkSize, decompressedChunkSize, compressedChunkSize: BGRALongWord;
chunks: array of TMemoryStream;
numChunk: integer;
chunkCount, i: integer;
decomp: Tdecompressionstream;
nextPos: BGRAInt64;
begin
{$hints off}
src.ReadBuffer(CompressionFlag, 1);
{$hints on}
if CompressionFlag = 1 then
dest.CopyFrom(src, uncompressedSize)
else
if CompressionFlag = 0 then
begin
maxChunkSize := BEReadLongword(src);
if maxChunkSize < 4 then
raise Exception.Create('Invalid max chunk size');
chunkCount := (uncompressedSize + maxChunkSize - 1) div maxChunkSize;
setlength(chunks, chunkCount);
for i := 0 to ChunkCount - 1 do
begin
numChunk := BEReadLongint(src);
if (numChunk < 0) or (numChunk >= chunkCount) then
raise Exception.Create('Chunk number out of bounds');
compressedChunkSize := BEReadLongword(src);
nextPos := src.Position + compressedChunkSize;
src.Position := src.Position + 10; //skip gzip header
decompressedChunkSize :=
min(maxChunkSize, uncompressedSize - BGRAInt64(numChunk) * BGRAInt64(maxChunkSize));
decomp := Tdecompressionstream.Create(src, True);
chunks[numChunk] := TMemoryStream.Create;
chunks[numChunk].CopyFrom(decomp, decompressedChunkSize);
FreeAndNil(decomp);
src.Position := nextPos;
end;
for i := 0 to ChunkCount - 1 do
begin
chunks[i].Position := 0;
dest.CopyFrom(chunks[i], chunks[i].size);
chunks[i].Free;
end;
setlength(chunks, 0);
end
else
raise Exception('Unknown compression flag (' + IntToStr(CompressionFlag) + ')');
end;
function TPaintDotNetFile.InternalGetLayer(num: integer): TSerializedClass;
var
layerList: TCustomSerializedObject;
begin
if Layers = nil then
raise Exception.Create('No layers available')
else
if (num < 0) or (num >= NbLayers) then
raise Exception.Create('Layer index out of bounds')
else
begin
layerList := Content.GetObjectField(Layers, '_items');
Result := Content.GetObject(layerList.FieldAsString[num]) as TSerializedClass;
end;
end;
function TPaintDotNetFile.InternalGetBlendOperation(layer: TSerializedClass): TBlendOperation;
var
prop, blendOp: TCustomSerializedObject;
blendName: string;
begin
if layer = nil then
Result := boTransparent
else
begin
prop := Content.GetObjectField(layer, 'properties');
if prop = nil then
Result := boTransparent
else
begin
blendOp := Content.GetObjectField(prop, 'blendOp');
if blendOp = nil then
Result := boTransparent
else
begin
blendName := blendOp.TypeAsString;
if (pos('+', blendName) <> 0) then
Delete(blendName, 1, pos('+', blendName));
if copy(blendName, length(blendName) - length('BlendOp') +
1, length('BlendOp')) = 'BlendOp' then
Delete(blendName, length(blendName) - length('BlendOp') +
1, length('BlendOp'));
if blendName = 'Normal' then
Result := boTransparent
else
if blendName = 'Multiply' then
Result := boLinearMultiply
else
if blendName = 'Additive' then
Result := boLinearAdd
else
if blendName = 'ColorBurn' then
Result := boColorBurn
else
if blendName = 'ColorDodge' then
Result := boColorDodge
else
if blendName = 'Reflect' then
Result := boReflect
else
if blendName = 'Glow' then
Result := boGlow
else
if blendName = 'Overlay' then
Result := boOverlay
else
if blendName = 'Difference' then
Result := boLinearDifference
else
if blendName = 'Negation' then
Result := boLinearNegation
else
if blendName = 'Lighten' then
Result := boLighten
else
if blendName = 'Darken' then
Result := boDarken
else
if blendName = 'Screen' then
Result := boScreen
else
if blendName = 'Xor' then
Result := boXor
else
Result := boTransparent;
end;
end;
end;
end;
function TPaintDotNetFile.InternalGetLayerVisible(layer: TSerializedClass): boolean;
var
prop: TCustomSerializedObject;
begin
if layer = nil then
Result := False
else
begin
prop := Content.GetObjectField(layer, 'Layer+properties');
if prop = nil then
Result := False
else
begin
Result := (Content.GetSimpleField(prop, 'visible') = 'True');
end;
end;
end;
function TPaintDotNetFile.InternalGetLayerOpacity(layer: TSerializedClass): byte;
var
prop: TCustomSerializedObject;
begin
if layer = nil then
Result := 0
else
begin
prop := Content.GetObjectField(layer, 'Layer+properties');
if prop = nil then
Result := 0
else
begin
Result := StrToInt(Content.GetSimpleField(prop, 'opacity'));
end;
end;
end;
var AlreadyRegistered: boolean;
procedure RegisterPaintNetFormat;
begin
if AlreadyRegistered then exit;
ImageHandlers.RegisterImageReader ('Paint.NET image', 'pdn', TFPReaderPaintDotNet);
RegisterLayeredBitmapReader('pdn', TPaintDotNetFile);
//TPicture.RegisterFileFormat('pdn', 'Paint.NET image', TPaintDotNetFile);
DefaultBGRAImageReader[ifPaintDotNet] := TFPReaderPaintDotNet;
AlreadyRegistered := true;
end;
end.