forked from WolvenKit/WolvenKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TargaImage.cs
2593 lines (2180 loc) · 100 KB
/
TargaImage.cs
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
// ==========================================================
// TargaImage
//
// Design and implementation by
// - David Polomis ([email protected])
//
//
// This source code, along with any associated files, is licensed under
// The Code Project Open License (CPOL) 1.02
// A copy of this license can be found in the CPOL.html file
// which was downloaded with this source code
// or at http://www.codeproject.com/info/cpol10.aspx
//
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
// INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS
// FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR
// NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE
// OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE
// DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY
// OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING,
// REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN
// ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS
// AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
//
// Use at your own risk!
//
// ==========================================================
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace WolvenKit.Render
{
internal static class TargaConstants
{
// constant byte lengths for various fields in the Targa format
internal const int HeaderByteLength = 18;
internal const int FooterByteLength = 26;
internal const int FooterSignatureOffsetFromEnd = 18;
internal const int FooterSignatureByteLength = 16;
internal const int FooterReservedCharByteLength = 1;
internal const int ExtensionAreaAuthorNameByteLength = 41;
internal const int ExtensionAreaAuthorCommentsByteLength = 324;
internal const int ExtensionAreaJobNameByteLength = 41;
internal const int ExtensionAreaSoftwareIDByteLength = 41;
internal const int ExtensionAreaSoftwareVersionLetterByteLength = 1;
internal const int ExtensionAreaColorCorrectionTableValueLength = 256;
internal const string TargaFooterASCIISignature = "TRUEVISION-XFILE";
}
/// <summary>
/// The Targa format of the file.
/// </summary>
public enum TGAFormat
{
/// <summary>
/// Unknown Targa Image format.
/// </summary>
UNKNOWN = 0,
/// <summary>
/// Original Targa Image format.
/// </summary>
/// <remarks>Targa Image does not have a Signature of ""TRUEVISION-XFILE"".</remarks>
ORIGINAL_TGA = 100,
/// <summary>
/// New Targa Image format
/// </summary>
/// <remarks>Targa Image has a TargaFooter with a Signature of ""TRUEVISION-XFILE"".</remarks>
NEW_TGA = 200
}
/// <summary>
/// Indicates the type of color map, if any, included with the image file.
/// </summary>
public enum ColorMapType : byte
{
/// <summary>
/// No color map was included in the file.
/// </summary>
NO_COLOR_MAP = 0,
/// <summary>
/// Color map was included in the file.
/// </summary>
COLOR_MAP_INCLUDED = 1
}
/// <summary>
/// The type of image read from the file.
/// </summary>
public enum ImageType : byte
{
/// <summary>
/// No image data was found in file.
/// </summary>
NO_IMAGE_DATA = 0,
/// <summary>
/// Image is an uncompressed, indexed color-mapped image.
/// </summary>
UNCOMPRESSED_COLOR_MAPPED = 1,
/// <summary>
/// Image is an uncompressed, RGB image.
/// </summary>
UNCOMPRESSED_TRUE_COLOR = 2,
/// <summary>
/// Image is an uncompressed, Greyscale image.
/// </summary>
UNCOMPRESSED_BLACK_AND_WHITE = 3,
/// <summary>
/// Image is a compressed, indexed color-mapped image.
/// </summary>
RUN_LENGTH_ENCODED_COLOR_MAPPED = 9,
/// <summary>
/// Image is a compressed, RGB image.
/// </summary>
RUN_LENGTH_ENCODED_TRUE_COLOR = 10,
/// <summary>
/// Image is a compressed, Greyscale image.
/// </summary>
RUN_LENGTH_ENCODED_BLACK_AND_WHITE = 11
}
/// <summary>
/// The top-to-bottom ordering in which pixel data is transferred from the file to the screen.
/// </summary>
public enum VerticalTransferOrder
{
/// <summary>
/// Unknown transfer order.
/// </summary>
UNKNOWN = -1,
/// <summary>
/// Transfer order of pixels is from the bottom to top.
/// </summary>
BOTTOM = 0,
/// <summary>
/// Transfer order of pixels is from the top to bottom.
/// </summary>
TOP = 1
}
/// <summary>
/// The left-to-right ordering in which pixel data is transferred from the file to the screen.
/// </summary>
public enum HorizontalTransferOrder
{
/// <summary>
/// Unknown transfer order.
/// </summary>
UNKNOWN = -1,
/// <summary>
/// Transfer order of pixels is from the right to left.
/// </summary>
RIGHT = 0,
/// <summary>
/// Transfer order of pixels is from the left to right.
/// </summary>
LEFT = 1
}
/// <summary>
/// Screen destination of first pixel based on the VerticalTransferOrder and HorizontalTransferOrder.
/// </summary>
public enum FirstPixelDestination
{
/// <summary>
/// Unknown first pixel destination.
/// </summary>
UNKNOWN = 0,
/// <summary>
/// First pixel destination is the top-left corner of the image.
/// </summary>
TOP_LEFT = 1,
/// <summary>
/// First pixel destination is the top-right corner of the image.
/// </summary>
TOP_RIGHT = 2,
/// <summary>
/// First pixel destination is the bottom-left corner of the image.
/// </summary>
BOTTOM_LEFT = 3,
/// <summary>
/// First pixel destination is the bottom-right corner of the image.
/// </summary>
BOTTOM_RIGHT = 4
}
/// <summary>
/// The RLE packet type used in a RLE compressed image.
/// </summary>
public enum RLEPacketType
{
/// <summary>
/// A raw RLE packet type.
/// </summary>
RAW = 0,
/// <summary>
/// A run-length RLE packet type.
/// </summary>
RUN_LENGTH = 1
}
/// <summary>
/// Reads and loads a Truevision TGA Format image file.
/// </summary>
public class TargaImage : IDisposable
{
private TargaHeader objTargaHeader = null;
private TargaExtensionArea objTargaExtensionArea = null;
private TargaFooter objTargaFooter = null;
private Bitmap bmpTargaImage = null;
private Bitmap bmpImageThumbnail = null;
private TGAFormat eTGAFormat = TGAFormat.UNKNOWN;
private string strFileName = string.Empty;
private int intStride = 0;
private int intPadding = 0;
private GCHandle ImageByteHandle;
private GCHandle ThumbnailByteHandle;
// Track whether Dispose has been called.
private bool disposed = false;
/// <summary>
/// Creates a new instance of the TargaImage object.
/// </summary>
public TargaImage()
{
this.objTargaFooter = new TargaFooter();
this.objTargaHeader = new TargaHeader();
this.objTargaExtensionArea = new TargaExtensionArea();
this.bmpTargaImage = null;
this.bmpImageThumbnail = null;
}
/// <summary>
/// Gets a TargaHeader object that holds the Targa Header information of the loaded file.
/// </summary>
public TargaHeader Header
{
get { return this.objTargaHeader; }
}
/// <summary>
/// Gets a TargaExtensionArea object that holds the Targa Extension Area information of the loaded file.
/// </summary>
public TargaExtensionArea ExtensionArea
{
get { return this.objTargaExtensionArea; }
}
/// <summary>
/// Gets a TargaExtensionArea object that holds the Targa Footer information of the loaded file.
/// </summary>
public TargaFooter Footer
{
get { return this.objTargaFooter; }
}
/// <summary>
/// Gets the Targa format of the loaded file.
/// </summary>
public TGAFormat Format
{
get { return this.eTGAFormat; }
}
/// <summary>
/// Gets a Bitmap representation of the loaded file.
/// </summary>
public Bitmap Image
{
get { return this.bmpTargaImage; }
}
/// <summary>
/// Gets the thumbnail of the loaded file if there is one in the file.
/// </summary>
public Bitmap Thumbnail
{
get { return this.bmpImageThumbnail; }
}
/// <summary>
/// Gets the full path and filename of the loaded file.
/// </summary>
public string FileName
{
get { return this.strFileName; }
}
/// <summary>
/// Gets the byte offset between the beginning of one scan line and the next. Used when loading the image into the Image Bitmap.
/// </summary>
/// <remarks>
/// The memory allocated for Microsoft Bitmaps must be aligned on a 32bit boundary.
/// The stride refers to the number of bytes allocated for one scanline of the bitmap.
/// </remarks>
public int Stride
{
get { return this.intStride; }
}
/// <summary>
/// Gets the number of bytes used to pad each scan line to meet the Stride value. Used when loading the image into the Image Bitmap.
/// </summary>
/// <remarks>
/// The memory allocated for Microsoft Bitmaps must be aligned on a 32bit boundary.
/// The stride refers to the number of bytes allocated for one scanline of the bitmap.
/// In your loop, you copy the pixels one scanline at a time and take into
/// consideration the amount of padding that occurs due to memory alignment.
/// </remarks>
public int Padding
{
get { return this.intPadding; }
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
/// <summary>
/// TargaImage deconstructor.
/// </summary>
~TargaImage()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
/// <summary>
/// Creates a new instance of the TargaImage object with strFileName as the image loaded.
/// </summary>
public TargaImage(string strFileName) : this()
{
// make sure we have a .tga file
if (System.IO.Path.GetExtension(strFileName).ToLower() == ".tga")
{
// make sure the file exists
if (System.IO.File.Exists(strFileName) == true)
{
this.strFileName = strFileName;
MemoryStream filestream = null;
BinaryReader binReader = null;
byte[] filebytes = null;
// load the file as an array of bytes
filebytes = System.IO.File.ReadAllBytes(this.strFileName);
if (filebytes != null && filebytes.Length > 0)
{
// create a seekable memory stream of the file bytes
using (filestream = new MemoryStream(filebytes))
{
if (filestream != null && filestream.Length > 0 && filestream.CanSeek == true)
{
// create a BinaryReader used to read the Targa file
using (binReader = new BinaryReader(filestream))
{
this.LoadTGAFooterInfo(binReader);
this.LoadTGAHeaderInfo(binReader);
this.LoadTGAExtensionArea(binReader);
this.LoadTGAImage(binReader);
}
}
else
throw new Exception(@"Error loading file, could not read file from disk.");
}
}
else
throw new Exception(@"Error loading file, could not read file from disk.");
}
else
throw new Exception(@"Error loading file, could not find file '" + strFileName + "' on disk.");
}
else
throw new Exception(@"Error loading file, file '" + strFileName + "' must have an extension of '.tga'.");
}
/// <summary>
/// Creates a new instance of the TargaImage object loading the image data from the provided stream.
/// </summary>
public TargaImage(Stream ImageStream)
: this()
{
if (ImageStream != null && ImageStream.Length > 0 && ImageStream.CanSeek == true)
{
// create a BinaryReader used to read the Targa file
using (BinaryReader binReader = new BinaryReader(ImageStream))
{
this.LoadTGAFooterInfo(binReader);
this.LoadTGAHeaderInfo(binReader);
this.LoadTGAExtensionArea(binReader);
this.LoadTGAImage(binReader);
}
}
else
throw new ArgumentException(@"Error loading image, Null, zero length or non-seekable stream provided.", "ImageStream");
}
/// <summary>
/// Loads the Targa Footer information from the file.
/// </summary>
/// <param name="binReader">A BinaryReader that points the loaded file byte stream.</param>
private void LoadTGAFooterInfo(BinaryReader binReader)
{
if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true)
{
try
{
// set the cursor at the beginning of the signature string.
binReader.BaseStream.Seek((TargaConstants.FooterSignatureOffsetFromEnd * -1), SeekOrigin.End);
// read the signature bytes and convert to ascii string
string Signature = System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.FooterSignatureByteLength)).TrimEnd('\0');
// do we have a proper signature
if (string.Compare(Signature, TargaConstants.TargaFooterASCIISignature) == 0)
{
// this is a NEW targa file.
// create the footer
this.eTGAFormat = TGAFormat.NEW_TGA;
// set cursor to beginning of footer info
binReader.BaseStream.Seek((TargaConstants.FooterByteLength * -1), SeekOrigin.End);
// read the Extension Area Offset value
int ExtOffset = binReader.ReadInt32();
// read the Developer Directory Offset value
int DevDirOff = binReader.ReadInt32();
// skip the signature we have already read it.
binReader.ReadBytes(TargaConstants.FooterSignatureByteLength);
// read the reserved character
string ResChar = System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.FooterReservedCharByteLength)).TrimEnd('\0');
// set all values to our TargaFooter class
this.objTargaFooter.SetExtensionAreaOffset(ExtOffset);
this.objTargaFooter.SetDeveloperDirectoryOffset(DevDirOff);
this.objTargaFooter.SetSignature(Signature);
this.objTargaFooter.SetReservedCharacter(ResChar);
}
else
{
// this is not an ORIGINAL targa file.
this.eTGAFormat = TGAFormat.ORIGINAL_TGA;
}
}
catch (Exception ex)
{
// clear all
this.ClearAll();
throw ex;
}
}
else
{
this.ClearAll();
throw new Exception(@"Error loading file, could not read file from disk.");
}
}
/// <summary>
/// Loads the Targa Header information from the file.
/// </summary>
/// <param name="binReader">A BinaryReader that points the loaded file byte stream.</param>
private void LoadTGAHeaderInfo(BinaryReader binReader)
{
if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true)
{
try
{
// set the cursor at the beginning of the file.
binReader.BaseStream.Seek(0, SeekOrigin.Begin);
// read the header properties from the file
this.objTargaHeader.SetImageIDLength(binReader.ReadByte());
this.objTargaHeader.SetColorMapType((ColorMapType)binReader.ReadByte());
this.objTargaHeader.SetImageType((ImageType)binReader.ReadByte());
this.objTargaHeader.SetColorMapFirstEntryIndex(binReader.ReadInt16());
this.objTargaHeader.SetColorMapLength(binReader.ReadInt16());
this.objTargaHeader.SetColorMapEntrySize(binReader.ReadByte());
this.objTargaHeader.SetXOrigin(binReader.ReadInt16());
this.objTargaHeader.SetYOrigin(binReader.ReadInt16());
this.objTargaHeader.SetWidth(binReader.ReadInt16());
this.objTargaHeader.SetHeight(binReader.ReadInt16());
byte pixeldepth = binReader.ReadByte();
switch (pixeldepth)
{
case 8:
case 16:
case 24:
case 32:
this.objTargaHeader.SetPixelDepth(pixeldepth);
break;
default:
this.ClearAll();
throw new Exception("Targa Image only supports 8, 16, 24, or 32 bit pixel depths.");
}
byte ImageDescriptor = binReader.ReadByte();
this.objTargaHeader.SetAttributeBits((byte)Utilities.GetBits(ImageDescriptor, 0, 4));
this.objTargaHeader.SetVerticalTransferOrder((VerticalTransferOrder)Utilities.GetBits(ImageDescriptor, 5, 1));
this.objTargaHeader.SetHorizontalTransferOrder((HorizontalTransferOrder)Utilities.GetBits(ImageDescriptor, 4, 1));
// load ImageID value if any
if (this.objTargaHeader.ImageIDLength > 0)
{
byte[] ImageIDValueBytes = binReader.ReadBytes(this.objTargaHeader.ImageIDLength);
this.objTargaHeader.SetImageIDValue(System.Text.Encoding.ASCII.GetString(ImageIDValueBytes).TrimEnd('\0'));
}
}
catch (Exception ex)
{
this.ClearAll();
throw ex;
}
// load color map if it's included and/or needed
// Only needed for UNCOMPRESSED_COLOR_MAPPED and RUN_LENGTH_ENCODED_COLOR_MAPPED
// image types. If color map is included for other file types we can ignore it.
if (this.objTargaHeader.ColorMapType == ColorMapType.COLOR_MAP_INCLUDED)
{
if (this.objTargaHeader.ImageType == ImageType.UNCOMPRESSED_COLOR_MAPPED ||
this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_COLOR_MAPPED)
{
if (this.objTargaHeader.ColorMapLength > 0)
{
try
{
for (int i = 0; i < this.objTargaHeader.ColorMapLength; i++)
{
int a = 0;
int r = 0;
int g = 0;
int b = 0;
// load each color map entry based on the ColorMapEntrySize value
switch (this.objTargaHeader.ColorMapEntrySize)
{
case 15:
byte[] color15 = binReader.ReadBytes(2);
// remember that the bytes are stored in reverse oreder
this.objTargaHeader.ColorMap.Add(Utilities.GetColorFrom2Bytes(color15[1], color15[0]));
break;
case 16:
byte[] color16 = binReader.ReadBytes(2);
// remember that the bytes are stored in reverse oreder
this.objTargaHeader.ColorMap.Add(Utilities.GetColorFrom2Bytes(color16[1], color16[0]));
break;
case 24:
b = Convert.ToInt32(binReader.ReadByte());
g = Convert.ToInt32(binReader.ReadByte());
r = Convert.ToInt32(binReader.ReadByte());
this.objTargaHeader.ColorMap.Add(System.Drawing.Color.FromArgb(r, g, b));
break;
case 32:
a = Convert.ToInt32(binReader.ReadByte());
b = Convert.ToInt32(binReader.ReadByte());
g = Convert.ToInt32(binReader.ReadByte());
r = Convert.ToInt32(binReader.ReadByte());
this.objTargaHeader.ColorMap.Add(System.Drawing.Color.FromArgb(a, r, g, b));
break;
default:
this.ClearAll();
throw new Exception("Targa Image only supports ColorMap Entry Sizes of 15, 16, 24 or 32 bits.");
}
}
}
catch (Exception ex)
{
this.ClearAll();
throw ex;
}
}
else
{
this.ClearAll();
throw new Exception("Image Type requires a Color Map and Color Map Length is zero.");
}
}
}
else
{
if (this.objTargaHeader.ImageType == ImageType.UNCOMPRESSED_COLOR_MAPPED ||
this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_COLOR_MAPPED)
{
this.ClearAll();
throw new Exception("Image Type requires a Color Map and there was not a Color Map included in the file.");
}
}
}
else
{
this.ClearAll();
throw new Exception(@"Error loading file, could not read file from disk.");
}
}
/// <summary>
/// Loads the Targa Extension Area from the file, if it exists.
/// </summary>
/// <param name="binReader">A BinaryReader that points the loaded file byte stream.</param>
private void LoadTGAExtensionArea(BinaryReader binReader)
{
if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true)
{
// is there an Extension Area in file
if (this.objTargaFooter.ExtensionAreaOffset > 0)
{
try
{
// set the cursor at the beginning of the Extension Area using ExtensionAreaOffset.
binReader.BaseStream.Seek(this.objTargaFooter.ExtensionAreaOffset, SeekOrigin.Begin);
// load the extension area fields from the file
this.objTargaExtensionArea.SetExtensionSize((int)(binReader.ReadInt16()));
this.objTargaExtensionArea.SetAuthorName(System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaAuthorNameByteLength)).TrimEnd('\0'));
this.objTargaExtensionArea.SetAuthorComments(System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaAuthorCommentsByteLength)).TrimEnd('\0'));
// get the date/time stamp of the file
Int16 iMonth = binReader.ReadInt16();
Int16 iDay = binReader.ReadInt16();
Int16 iYear = binReader.ReadInt16();
Int16 iHour = binReader.ReadInt16();
Int16 iMinute = binReader.ReadInt16();
Int16 iSecond = binReader.ReadInt16();
DateTime dtstamp;
string strStamp = iMonth.ToString() + @"/" + iDay.ToString() + @"/" + iYear.ToString() + @" ";
strStamp += iHour.ToString() + @":" + iMinute.ToString() + @":" + iSecond.ToString();
if (DateTime.TryParse(strStamp, out dtstamp) == true)
this.objTargaExtensionArea.SetDateTimeStamp(dtstamp);
this.objTargaExtensionArea.SetJobName(System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaJobNameByteLength)).TrimEnd('\0'));
// get the job time of the file
iHour = binReader.ReadInt16();
iMinute = binReader.ReadInt16();
iSecond = binReader.ReadInt16();
TimeSpan ts = new TimeSpan((int)iHour, (int)iMinute, (int)iSecond);
this.objTargaExtensionArea.SetJobTime(ts);
this.objTargaExtensionArea.SetSoftwareID(System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaSoftwareIDByteLength)).TrimEnd('\0'));
// get the version number and letter from file
float iVersionNumber = (float)binReader.ReadInt16() / 100.0F;
string strVersionLetter = System.Text.Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaSoftwareVersionLetterByteLength)).TrimEnd('\0');
this.objTargaExtensionArea.SetSoftwareID(iVersionNumber.ToString(@"F2") + strVersionLetter);
// get the color key of the file
int a = (int)binReader.ReadByte();
int r = (int)binReader.ReadByte();
int b = (int)binReader.ReadByte();
int g = (int)binReader.ReadByte();
this.objTargaExtensionArea.SetKeyColor(Color.FromArgb(a, r, g, b));
this.objTargaExtensionArea.SetPixelAspectRatioNumerator((int)binReader.ReadInt16());
this.objTargaExtensionArea.SetPixelAspectRatioDenominator((int)binReader.ReadInt16());
this.objTargaExtensionArea.SetGammaNumerator((int)binReader.ReadInt16());
this.objTargaExtensionArea.SetGammaDenominator((int)binReader.ReadInt16());
this.objTargaExtensionArea.SetColorCorrectionOffset(binReader.ReadInt32());
this.objTargaExtensionArea.SetPostageStampOffset(binReader.ReadInt32());
this.objTargaExtensionArea.SetScanLineOffset(binReader.ReadInt32());
this.objTargaExtensionArea.SetAttributesType((int)binReader.ReadByte());
// load Scan Line Table from file if any
if (this.objTargaExtensionArea.ScanLineOffset > 0)
{
binReader.BaseStream.Seek(this.objTargaExtensionArea.ScanLineOffset, SeekOrigin.Begin);
for (int i = 0; i < this.objTargaHeader.Height; i++)
{
this.objTargaExtensionArea.ScanLineTable.Add(binReader.ReadInt32());
}
}
// load Color Correction Table from file if any
if (this.objTargaExtensionArea.ColorCorrectionOffset > 0)
{
binReader.BaseStream.Seek(this.objTargaExtensionArea.ColorCorrectionOffset, SeekOrigin.Begin);
for (int i = 0; i < TargaConstants.ExtensionAreaColorCorrectionTableValueLength; i++)
{
a = (int)binReader.ReadInt16();
r = (int)binReader.ReadInt16();
b = (int)binReader.ReadInt16();
g = (int)binReader.ReadInt16();
this.objTargaExtensionArea.ColorCorrectionTable.Add(Color.FromArgb(a, r, g, b));
}
}
}
catch (Exception ex)
{
this.ClearAll();
throw ex;
}
}
}
else
{
this.ClearAll();
throw new Exception(@"Error loading file, could not read file from disk.");
}
}
/// <summary>
/// Reads the image data bytes from the file. Handles Uncompressed and RLE Compressed image data.
/// Uses FirstPixelDestination to properly align the image.
/// </summary>
/// <param name="binReader">A BinaryReader that points the loaded file byte stream.</param>
/// <returns>An array of bytes representing the image data in the proper alignment.</returns>
private byte[] LoadImageBytes(BinaryReader binReader)
{
// read the image data into a byte array
// take into account stride has to be a multiple of 4
// use padding to make sure multiple of 4
byte[] data = null;
if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true)
{
if (this.objTargaHeader.ImageDataOffset > 0)
{
// padding bytes
byte[] padding = new byte[this.intPadding];
MemoryStream msData = null;
System.Collections.Generic.List<System.Collections.Generic.List<byte>> rows = null;
System.Collections.Generic.List<byte> row = null;
rows = new System.Collections.Generic.List<System.Collections.Generic.List<byte>>();
row = new System.Collections.Generic.List<byte>();
// seek to the beginning of the image data using the ImageDataOffset value
binReader.BaseStream.Seek(this.objTargaHeader.ImageDataOffset, SeekOrigin.Begin);
// get the size in bytes of each row in the image
int intImageRowByteSize = (int)this.objTargaHeader.Width * ((int)this.objTargaHeader.BytesPerPixel);
// get the size in bytes of the whole image
int intImageByteSize = intImageRowByteSize * (int)this.objTargaHeader.Height;
// is this a RLE compressed image type
if (this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_BLACK_AND_WHITE ||
this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_COLOR_MAPPED ||
this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_TRUE_COLOR)
{
#region COMPRESSED
// RLE Packet info
byte bRLEPacket = 0;
int intRLEPacketType = -1;
int intRLEPixelCount = 0;
byte[] bRunLengthPixel = null;
// used to keep track of bytes read
int intImageBytesRead = 0;
int intImageRowBytesRead = 0;
// keep reading until we have the all image bytes
while (intImageBytesRead < intImageByteSize)
{
// get the RLE packet
bRLEPacket = binReader.ReadByte();
intRLEPacketType = Utilities.GetBits(bRLEPacket, 7, 1);
intRLEPixelCount = Utilities.GetBits(bRLEPacket, 0, 7) + 1;
// check the RLE packet type
if ((RLEPacketType)intRLEPacketType == RLEPacketType.RUN_LENGTH)
{
// get the pixel color data
bRunLengthPixel = binReader.ReadBytes((int)this.objTargaHeader.BytesPerPixel);
// add the number of pixels specified using the read pixel color
for (int i = 0; i < intRLEPixelCount; i++)
{
foreach (byte b in bRunLengthPixel)
row.Add(b);
// increment the byte counts
intImageRowBytesRead += bRunLengthPixel.Length;
intImageBytesRead += bRunLengthPixel.Length;
// if we have read a full image row
// add the row to the row list and clear it
// restart row byte count
if (intImageRowBytesRead == intImageRowByteSize)
{
rows.Add(row);
row = null;
row = new System.Collections.Generic.List<byte>();
intImageRowBytesRead = 0;
}
}
}
else if ((RLEPacketType)intRLEPacketType == RLEPacketType.RAW)
{
// get the number of bytes to read based on the read pixel count
int intBytesToRead = intRLEPixelCount * (int)this.objTargaHeader.BytesPerPixel;
// read each byte
for (int i = 0; i < intBytesToRead; i++)
{
row.Add(binReader.ReadByte());
// increment the byte counts
intImageBytesRead++;
intImageRowBytesRead++;
// if we have read a full image row
// add the row to the row list and clear it
// restart row byte count
if (intImageRowBytesRead == intImageRowByteSize)
{
rows.Add(row);
row = null;
row = new System.Collections.Generic.List<byte>();
intImageRowBytesRead = 0;
}
}
}
}
#endregion
}
else
{
#region NON-COMPRESSED
// loop through each row in the image
for (int i = 0; i < (int)this.objTargaHeader.Height; i++)
{
// loop through each byte in the row
for (int j = 0; j < intImageRowByteSize; j++)
{
// add the byte to the row
row.Add(binReader.ReadByte());
}
// add row to the list of rows
rows.Add(row);
// create a new row
row = null;
row = new System.Collections.Generic.List<byte>();
}
#endregion
}
// flag that states whether or not to reverse the location of all rows.
bool blnRowsReverse = false;
// flag that states whether or not to reverse the bytes in each row.
bool blnEachRowReverse = false;
// use FirstPixelDestination to determine the alignment of the
// image data byte
switch (this.objTargaHeader.FirstPixelDestination)
{
case FirstPixelDestination.TOP_LEFT:
blnRowsReverse = false;
blnEachRowReverse = true;
break;
case FirstPixelDestination.TOP_RIGHT:
blnRowsReverse = false;
blnEachRowReverse = false;
break;
case FirstPixelDestination.BOTTOM_LEFT:
blnRowsReverse = true;
blnEachRowReverse = true;
break;
case FirstPixelDestination.BOTTOM_RIGHT:
case FirstPixelDestination.UNKNOWN:
blnRowsReverse = true;
blnEachRowReverse = false;
break;
}
// write the bytes from each row into a memory stream and get the
// resulting byte array
using (msData = new MemoryStream())
{
// do we reverse the rows in the row list.
if (blnRowsReverse == true)
rows.Reverse();
// go through each row
for (int i = 0; i < rows.Count; i++)
{
// do we reverse the bytes in the row
if (blnEachRowReverse == true)
rows[i].Reverse();