-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFreeImageWrapper.cs
More file actions
5311 lines (5013 loc) · 186 KB
/
FreeImageWrapper.cs
File metadata and controls
5311 lines (5013 loc) · 186 KB
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
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net)
// - Carsten Klein (cklein05@users.sourceforge.net)
//
// Contributors:
// - David Boland (davidboland@vodafone.ie)
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// 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!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.19 $
// $Date: 2011/10/02 13:00:45 $
// $Id: FreeImageWrapper.cs,v 1.19 2011/10/02 13:00:45 drolon Exp $
// ==========================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using FreeImageAPI.IO;
using FreeImageAPI.Metadata;
namespace FreeImageAPI
{
/// <summary>
/// Static class importing functions from the FreeImage library
/// and providing additional functions.
/// </summary>
public static partial class FreeImage
{
#region Constants
/// <summary>
/// Array containing all 'FREE_IMAGE_MDMODEL's.
/// </summary>
public static readonly FREE_IMAGE_MDMODEL[] FREE_IMAGE_MDMODELS =
(FREE_IMAGE_MDMODEL[])Enum.GetValues(typeof(FREE_IMAGE_MDMODEL));
/// <summary>
/// Stores handles used to read from streams.
/// </summary>
private static Dictionary<FIMULTIBITMAP, fi_handle> streamHandles =
new Dictionary<FIMULTIBITMAP, fi_handle>();
/// <summary>
/// Version of the wrapper library.
/// </summary>
private static Version WrapperVersion;
private const int DIB_RGB_COLORS = 0;
private const int DIB_PAL_COLORS = 1;
private const int CBM_INIT = 0x4;
/// <summary>
/// An uncompressed format.
/// </summary>
public const int BI_RGB = 0;
/// <summary>
/// A run-length encoded (RLE) format for bitmaps with 8 bpp. The compression format is a 2-byte
/// format consisting of a count byte followed by a byte containing a color index.
/// </summary>
public const int BI_RLE8 = 1;
/// <summary>
/// An RLE format for bitmaps with 4 bpp. The compression format is a 2-byte format consisting
/// of a count byte followed by two word-length color indexes.
/// </summary>
public const int BI_RLE4 = 2;
/// <summary>
/// Specifies that the bitmap is not compressed and that the color table consists of three
/// <b>DWORD</b> color masks that specify the red, green, and blue components, respectively,
/// of each pixel. This is valid when used with 16- and 32-bpp bitmaps.
/// </summary>
public const int BI_BITFIELDS = 3;
/// <summary>
/// <b>Windows 98/Me, Windows 2000/XP:</b> Indicates that the image is a JPEG image.
/// </summary>
public const int BI_JPEG = 4;
/// <summary>
/// <b>Windows 98/Me, Windows 2000/XP:</b> Indicates that the image is a PNG image.
/// </summary>
public const int BI_PNG = 5;
#endregion
#region General functions
/// <summary>
/// Returns the internal version of this FreeImage .NET wrapper.
/// </summary>
/// <returns>The internal version of this FreeImage .NET wrapper.</returns>
public static Version GetWrapperVersion()
{
if (WrapperVersion == null)
{
WrapperVersion = new Version("3.17.0");
}
return WrapperVersion;
}
/// <summary>
/// Returns the version of the native FreeImage library.
/// </summary>
/// <returns>The version of the native FreeImage library.</returns>
public static Version GetNativeVersion()
{
return new Version(GetVersion());
}
/// <summary>
/// Returns a value indicating if the FreeImage library is available or not.
/// See remarks for further details.
/// </summary>
/// <returns><c>false</c> if the file is not available or out of date;
/// <c>true</c>, otherwise.</returns>
/// <remarks>
/// The FreeImage.NET library is a wrapper for the native C++ library
/// (FreeImage.dll ... dont mix ist up with this library FreeImageNet.dll).
/// The native library <b>must</b> be either in the same folder as the program's
/// executable or in a folder contained in the envirent variable <i>PATH</i>
/// (for example %WINDIR%\System32).<para/>
/// Further more must both libraries, including the program itself,
/// be the same architecture (x86 or x64).
/// </remarks>
public static bool IsAvailable()
{
try
{
// Call a static fast executing function
Version nativeVersion = new Version(GetVersion());
Version wrapperVersion = GetWrapperVersion();
// No exception thrown, the library seems to be present
return
(nativeVersion.Major > wrapperVersion.Major) ||
((nativeVersion.Major == wrapperVersion.Major) && (nativeVersion.Minor > wrapperVersion.Minor)) ||
((nativeVersion.Major == wrapperVersion.Major) && (nativeVersion.Minor == wrapperVersion.Minor) && (nativeVersion.Build >= wrapperVersion.Build));
}
catch (DllNotFoundException)
{
return false;
}
// NOT FOUND - ABORT
// catch (EntryPointNotFoundException)
// {
// return false;
// }
catch (BadImageFormatException)
{
return false;
}
}
#endregion
#region Bitmap management functions
/// <summary>
/// Creates a new bitmap in memory.
/// </summary>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new Bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP Allocate(int width, int height, int bpp)
{
return Allocate(width, height, bpp, 0, 0, 0);
}
/// <summary>
/// Creates a new bitmap in memory.
/// </summary>
/// <param name="type">Type of the image.</param>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new Bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP AllocateT(FREE_IMAGE_TYPE type, int width, int height, int bpp)
{
return AllocateT(type, width, height, bpp, 0, 0, 0);
}
/// <summary>
/// Allocates a new image of the specified width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmaps.</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="Allocate"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="Allocate"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>.
/// So, please refer to the documentation of <see cref="FillBackground<T>"/> to
/// learn more about parameters <paramref name="color"/> and <paramref name="options"/>.
/// <para/>
/// The palette specified through parameter <paramref name="palette"/> is only copied to the
/// newly created image, if the desired bit depth is smaller than or equal to 8 bits per pixel.
/// In other words, the <paramref name="palette"/> parameter is only taken into account for
/// palletized images. So, for an 8-bit image, the length is 256, for an 4-bit image it is 16
/// and it is 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified <paramref name="color"/> is applied to the palette entry,
/// specified by the background color's <see cref="RGBQUAD.rgbReserved"/> field.
/// The image is then filled with this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="Allocate"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateEx(int width, int height, int bpp,
RGBQUAD? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette)
{
return AllocateEx(width, height, bpp, color, options, palette, 0, 0, 0);
}
/// <summary>
/// Allocates a new image of the specified width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmaps.</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <param name="red_mask">Red part of the color layout.
/// eg: 0xFF0000</param>
/// <param name="green_mask">Green part of the color layout.
/// eg: 0x00FF00</param>
/// <param name="blue_mask">Blue part of the color layout.
/// eg: 0x0000FF</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="Allocate"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="Allocate"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>.
/// So, please refer to the documentation of <see cref="FillBackground<T>"/> to
/// learn more about parameters <paramref name="color"/> and <paramref name="options"/>.
/// <para/>
/// The palette specified through parameter <paramref name="palette"/> is only copied to the
/// newly created image, if the desired bit depth is smaller than or equal to 8 bits per pixel.
/// In other words, the <paramref name="palette"/> parameter is only taken into account for
/// palletized images. So, for an 8-bit image, the length is 256, for an 4-bit image it is 16
/// and it is 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified <paramref name="color"/> is applied to the palette entry,
/// specified by the background color's <see cref="RGBQUAD.rgbReserved"/> field.
/// The image is then filled with this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="Allocate"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateEx(int width, int height, int bpp,
RGBQUAD? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette,
uint red_mask, uint green_mask, uint blue_mask)
{
if ((palette != null) && (bpp <= 8) && (palette.Length < (1 << bpp)))
return FIBITMAP.Zero;
if (color.HasValue)
{
GCHandle handle = new GCHandle();
try
{
RGBQUAD[] buffer = new RGBQUAD[] { color.Value };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return AllocateEx(width, height, bpp, handle.AddrOfPinnedObject(),
options, palette, red_mask, green_mask, blue_mask);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
else
{
return AllocateEx(width, height, bpp, IntPtr.Zero,
options, palette, red_mask, green_mask, blue_mask);
}
}
/// <summary>
/// Allocates a new image of the specified type, width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <typeparam name="T">The type of the specified color.</typeparam>
/// <param name="type">Type of the image.</param>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="AllocateT"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="AllocateT"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>. So, please refer to the
/// documentation of <see cref="FillBackground<T>"/> to learn more about parameters color and options.
/// <para/>
/// The palette specified through parameter palette is only copied to the newly created
/// image, if its image type is <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> and the desired bit
/// depth is smaller than or equal to 8 bits per pixel. In other words, the <paramref name="palette"/>
/// palette is only taken into account for palletized images. However, if the preceding conditions
/// match and if <paramref name="palette"/> is not <c>null</c>, the palette is assumed to be at
/// least as large as the size of a fully populated palette for the desired bit depth.
/// So, for an 8-bit image, this length is 256, for an 4-bit image it is 16 and it is
/// 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified color is applied to the palette entry, specified by the
/// background color's <see cref="RGBQUAD.rgbReserved"/> field. The image is then filled with
/// this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="AllocateT"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateExT<T>(FREE_IMAGE_TYPE type, int width, int height, int bpp,
T? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette) where T : struct
{
return AllocateExT(type, width, height, bpp, color, options, palette, 0, 0, 0);
}
/// <summary>
/// Allocates a new image of the specified type, width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <typeparam name="T">The type of the specified color.</typeparam>
/// <param name="type">Type of the image.</param>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <param name="red_mask">Red part of the color layout.
/// eg: 0xFF0000</param>
/// <param name="green_mask">Green part of the color layout.
/// eg: 0x00FF00</param>
/// <param name="blue_mask">Blue part of the color layout.
/// eg: 0x0000FF</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="AllocateT"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="AllocateT"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>. So, please refer to the
/// documentation of <see cref="FillBackground<T>"/> to learn more about parameters color and options.
/// <para/>
/// The palette specified through parameter palette is only copied to the newly created
/// image, if its image type is <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> and the desired bit
/// depth is smaller than or equal to 8 bits per pixel. In other words, the <paramref name="palette"/>
/// palette is only taken into account for palletized images. However, if the preceding conditions
/// match and if <paramref name="palette"/> is not <c>null</c>, the palette is assumed to be at
/// least as large as the size of a fully populated palette for the desired bit depth.
/// So, for an 8-bit image, this length is 256, for an 4-bit image it is 16 and it is
/// 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified color is applied to the palette entry, specified by the
/// background color's <see cref="RGBQUAD.rgbReserved"/> field. The image is then filled with
/// this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="AllocateT"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateExT<T>(FREE_IMAGE_TYPE type, int width, int height, int bpp,
T? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette,
uint red_mask, uint green_mask, uint blue_mask) where T : struct
{
if ((palette != null) && (bpp <= 8) && (palette.Length < (1 << bpp)))
return FIBITMAP.Zero;
if (color.HasValue)
{
if (!CheckColorType(type, color.Value))
return FIBITMAP.Zero;
GCHandle handle = new GCHandle();
try
{
T[] buffer = new T[] { color.Value };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return AllocateExT(type, width, height, bpp, handle.AddrOfPinnedObject(),
options, palette, red_mask, green_mask, blue_mask);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
else
{
return AllocateExT(type, width, height, bpp, IntPtr.Zero,
options, palette, red_mask, green_mask, blue_mask);
}
}
/// <summary>
/// Converts a FreeImage bitmap to a .NET <see cref="System.Drawing.Bitmap"/>.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>The converted .NET <see cref="System.Drawing.Bitmap"/>.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The image type of <paramref name="dib"/> is not FIT_BITMAP.</exception>
// public static Bitmap GetBitmap(FIBITMAP dib)
// {
// return GetBitmap(dib, true);
// }
/// <summary>
/// Converts a FreeImage bitmap to a .NET <see cref="System.Drawing.Bitmap"/>.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="copyMetadata">When true existing metadata will be copied.</param>
/// <returns>The converted .NET <see cref="System.Drawing.Bitmap"/>.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The image type of <paramref name="dib"/> is not FIT_BITMAP.</exception>
// internal static Bitmap GetBitmap(FIBITMAP dib, bool copyMetadata)
// {
// if (dib.IsNull)
// {
// throw new ArgumentNullException("dib");
// }
// if (GetImageType(dib) != FREE_IMAGE_TYPE.FIT_BITMAP)
// {
// throw new ArgumentException("Only bitmaps with type of FIT_BITMAP can be converted.");
// }
//
// PixelFormat format = GetPixelFormat(dib);
//
// if ((format == PixelFormat.Undefined) && (GetBPP(dib) == 16u))
// {
// throw new ArgumentException("Only 16bit 555 and 565 are supported.");
// }
//
// int height = (int)GetHeight(dib);
// int width = (int)GetWidth(dib);
// int pitch = (int)GetPitch(dib);
//
// Bitmap result = new Bitmap(width, height, format);
// BitmapData data;
// // Locking the complete bitmap in writeonly mode
// data = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, format);
// // Writing the bitmap data directly into the new created .NET bitmap.
// ConvertToRawBits(data.Scan0, dib, pitch, GetBPP(dib),
// GetRedMask(dib), GetGreenMask(dib), GetBlueMask(dib), true);
// // Unlock the bitmap
// result.UnlockBits(data);
// // Apply the bitmap resolution
// if((GetResolutionX(dib) > 0) && (GetResolutionY(dib) > 0))
// {
// // SetResolution will throw an exception when zero values are given on input
// result.SetResolution(GetResolutionX(dib), GetResolutionY(dib));
// }
// // Check whether the bitmap has a palette
// if (GetPalette(dib) != IntPtr.Zero)
// {
// // Get the bitmaps palette to apply changes
// ColorPalette palette = result.Palette;
// // Get the orgininal palette
// Color[] colorPalette = new Palette(dib).ColorData;
// // Get the maximum number of palette entries to copy
// int entriesToCopy = Math.Min(colorPalette.Length, palette.Entries.Length);
//
// // Check whether the bitmap is transparent
// if (IsTransparent(dib))
// {
// byte[] transTable = GetTransparencyTableEx(dib);
// int i = 0;
// int maxEntriesWithTrans = Math.Min(entriesToCopy, transTable.Length);
// // Copy palette entries and include transparency
// for (; i < maxEntriesWithTrans; i++)
// {
// palette.Entries[i] = Color.FromArgb(transTable[i], colorPalette[i]);
// }
// // Copy palette entries and that have no transparancy
// for (; i < entriesToCopy; i++)
// {
// palette.Entries[i] = Color.FromArgb(0xFF, colorPalette[i]);
// }
// }
// else
// {
// for (int i = 0; i < entriesToCopy; i++)
// {
// palette.Entries[i] = colorPalette[i];
// }
// }
//
// // Set the bitmaps palette
// result.Palette = palette;
// }
// // Copy metadata
// if (copyMetadata)
// {
// try
// {
// List<PropertyItem> list = new List<PropertyItem>();
// // Get a list of all types
// FITAG tag;
// FIMETADATA mData;
// foreach (FREE_IMAGE_MDMODEL model in FREE_IMAGE_MDMODELS)
// {
// // Get a unique search handle
// mData = FindFirstMetadata(model, dib, out tag);
// // Check if metadata exists for this type
// if (mData.IsNull) continue;
// do
// {
// PropertyItem propItem = CreatePropertyItem();
// propItem.Len = (int)GetTagLength(tag);
// propItem.Id = (int)GetTagID(tag);
// propItem.Type = (short)GetTagType(tag);
// byte[] buffer = new byte[propItem.Len];
//
// unsafe
// {
// byte* src = (byte*)GetTagValue(tag);
// fixed (byte* dst = buffer)
// {
// CopyMemory(dst, src, (uint)propItem.Len);
// }
// }
//
// propItem.Value = buffer;
// list.Add(propItem);
// }
// while (FindNextMetadata(mData, out tag));
// FindCloseMetadata(mData);
// }
// foreach (PropertyItem propItem in list)
// {
// result.SetPropertyItem(propItem);
// }
// }
// catch
// {
// }
// }
// return result;
// }
/// <summary>
/// Converts an .NET <see cref="System.Drawing.Bitmap"/> into a FreeImage bitmap.
/// </summary>
/// <param name="bitmap">The <see cref="System.Drawing.Bitmap"/> to convert.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
// public static FIBITMAP CreateFromBitmap(Bitmap bitmap)
// {
// return CreateFromBitmap(bitmap, false);
// }
/// <summary>
/// Converts an .NET <see cref="System.Drawing.Bitmap"/> into a FreeImage bitmap.
/// </summary>
/// <param name="bitmap">The <see cref="System.Drawing.Bitmap"/> to convert.</param>
/// <param name="copyMetadata">When true existing metadata will be copied.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
// internal static FIBITMAP CreateFromBitmap(Bitmap bitmap, bool copyMetadata)
// {
// if (bitmap == null)
// {
// throw new ArgumentNullException("bitmap");
// }
// uint bpp, red_mask, green_mask, blue_mask;
// FREE_IMAGE_TYPE type;
// if (!GetFormatParameters(bitmap.PixelFormat, out type, out bpp, out red_mask, out green_mask, out blue_mask))
// {
// throw new ArgumentException("The bitmaps pixelformat is invalid.");
// }
//
// // Locking the complete bitmap in readonly mode
// BitmapData data = bitmap.LockBits(
// new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
// // Copying the bitmap data directly from the .NET bitmap
// FIBITMAP result = ConvertFromRawBits(
// data.Scan0,
// type,
// data.Width,
// data.Height,
// data.Stride,
// bpp,
// red_mask,
// green_mask,
// blue_mask,
// true);
// bitmap.UnlockBits(data);
// // Handle palette
// if (GetPalette(result) != IntPtr.Zero)
// {
// Palette palette = new Palette(result);
// Color[] colors = bitmap.Palette.Entries;
// // Only copy available palette entries
// int entriesToCopy = Math.Min(palette.Length, colors.Length);
// byte[] transTable = new byte[entriesToCopy];
// for (int i = 0; i < entriesToCopy; i++)
// {
// RGBQUAD color = (RGBQUAD)colors[i];
// color.rgbReserved = 0x00;
// palette[i] = color;
// transTable[i] = colors[i].A;
// }
// if ((bitmap.Flags & (int)ImageFlags.HasAlpha) != 0)
// {
// FreeImage.SetTransparencyTable(result, transTable);
// }
// }
// // Handle meta data
// // Disabled
// //if (copyMetadata)
// //{
// // foreach (PropertyItem propItem in bitmap.PropertyItems)
// // {
// // FITAG tag = CreateTag();
// // SetTagLength(tag, (uint)propItem.Len);
// // SetTagID(tag, (ushort)propItem.Id);
// // SetTagType(tag, (FREE_IMAGE_MDTYPE)propItem.Type);
// // SetTagValue(tag, propItem.Value);
// // SetMetadata(FREE_IMAGE_MDMODEL.FIMD_EXIF_EXIF, result, "", tag);
// // }
// //}
// return result;
// }
/// <summary>
/// Converts a raw bitmap to a FreeImage bitmap.
/// </summary>
/// <param name="bits">Array of bytes containing the raw bitmap.</param>
/// <param name="type">The type of the raw bitmap.</param>
/// <param name="width">The width in pixels of the raw bitmap.</param>
/// <param name="height">The height in pixels of the raw bitmap.</param>
/// <param name="pitch">Defines the total width of a scanline in the raw bitmap,
/// including padding bytes.</param>
/// <param name="bpp">The bit depth (bits per pixel) of the raw bitmap.</param>
/// <param name="red_mask">The bit mask describing the bits used to store a single
/// pixel's red component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="green_mask">The bit mask describing the bits used to store a single
/// pixel's green component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="blue_mask">The bit mask describing the bits used to store a single
/// pixel's blue component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="topdown">If true, the raw bitmap is stored in top-down order (top-left pixel first)
/// and in bottom-up order (bottom-left pixel first) otherwise.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static unsafe FIBITMAP ConvertFromRawBits(
byte[] bits,
FREE_IMAGE_TYPE type,
int width,
int height,
int pitch,
uint bpp,
uint red_mask,
uint green_mask,
uint blue_mask,
bool topdown)
{
fixed (byte* ptr = bits)
{
return ConvertFromRawBits(
(IntPtr)ptr,
type,
width,
height,
pitch,
bpp,
red_mask,
green_mask,
blue_mask,
topdown);
}
}
/// <summary>
/// Converts a raw bitmap to a FreeImage bitmap.
/// </summary>
/// <param name="bits">Pointer to the memory block containing the raw bitmap.</param>
/// <param name="type">The type of the raw bitmap.</param>
/// <param name="width">The width in pixels of the raw bitmap.</param>
/// <param name="height">The height in pixels of the raw bitmap.</param>
/// <param name="pitch">Defines the total width of a scanline in the raw bitmap,
/// including padding bytes.</param>
/// <param name="bpp">The bit depth (bits per pixel) of the raw bitmap.</param>
/// <param name="red_mask">The bit mask describing the bits used to store a single
/// pixel's red component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="green_mask">The bit mask describing the bits used to store a single
/// pixel's green component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="blue_mask">The bit mask describing the bits used to store a single
/// pixel's blue component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="topdown">If true, the raw bitmap is stored in top-down order (top-left pixel first)
/// and in bottom-up order (bottom-left pixel first) otherwise.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static unsafe FIBITMAP ConvertFromRawBits(
IntPtr bits,
FREE_IMAGE_TYPE type,
int width,
int height,
int pitch,
uint bpp,
uint red_mask,
uint green_mask,
uint blue_mask,
bool topdown)
{
byte* addr = (byte*)bits;
if ((addr == null) || (width <= 0) || (height <= 0))
{
return FIBITMAP.Zero;
}
FIBITMAP dib = AllocateT(type, width, height, (int)bpp, red_mask, green_mask, blue_mask);
if (dib != FIBITMAP.Zero)
{
if (topdown)
{
for (int i = height - 1; i >= 0; --i)
{
CopyMemory((byte*)GetScanLine(dib, i), addr, (int)GetLine(dib));
addr += pitch;
}
}
else
{
for (int i = 0; i < height; ++i)
{
CopyMemory((byte*)GetScanLine(dib, i), addr, (int)GetLine(dib));
addr += pitch;
}
}
}
return dib;
}
// /// <summary>
// /// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
// /// </summary>
// /// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
// /// <param name="filename">Name of the file to save to.</param>
// /// <returns>Returns true on success, false on failure.</returns>
// /// <exception cref="ArgumentNullException">
// /// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
// /// <exception cref="ArgumentException">
// /// The bitmaps pixelformat is invalid.</exception>
// public static bool SaveBitmap(Bitmap bitmap, string filename)
// {
// return SaveBitmap(
// bitmap,
// filename,
// FREE_IMAGE_FORMAT.FIF_UNKNOWN,
// FREE_IMAGE_SAVE_FLAGS.DEFAULT);
// }
//
// /// <summary>
// /// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
// /// </summary>
// /// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
// /// <param name="filename">Name of the file to save to.</param>
// /// <param name="flags">Flags to enable or disable plugin-features.</param>
// /// <returns>Returns true on success, false on failure.</returns>
// /// <exception cref="ArgumentNullException">
// /// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
// /// <exception cref="ArgumentException">
// /// The bitmaps pixelformat is invalid.</exception>
// public static bool SaveBitmap(Bitmap bitmap, string filename, FREE_IMAGE_SAVE_FLAGS flags)
// {
// return SaveBitmap(
// bitmap,
// filename,
// FREE_IMAGE_FORMAT.FIF_UNKNOWN,
// flags);
// }
//
// /// <summary>
// /// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
// /// </summary>
// /// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
// /// <param name="filename">Name of the file to save to.</param>
// /// <param name="format">Format of the bitmap. If the format should be taken from the
// /// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
// /// <param name="flags">Flags to enable or disable plugin-features.</param>
// /// <returns>Returns true on success, false on failure.</returns>
// /// <exception cref="ArgumentNullException">
// /// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
// /// <exception cref="ArgumentException">
// /// The bitmaps pixelformat is invalid.</exception>
// public static bool SaveBitmap(
// Bitmap bitmap,
// string filename,
// FREE_IMAGE_FORMAT format,
// FREE_IMAGE_SAVE_FLAGS flags)
// {
// FIBITMAP dib = CreateFromBitmap(bitmap);
// bool result = SaveEx(dib, filename, format, flags);
// Unload(dib);
// return result;
// }
/// <summary>
/// Loads a FreeImage bitmap.
/// The file will be loaded with default loading flags.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return LoadEx(filename, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// Load flags can be provided by the flags parameter.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename, FREE_IMAGE_LOAD_FLAGS flags)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return LoadEx(filename, flags, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
/// real format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// The file will be loaded with default loading flags.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadEx it will be returned in format.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename, ref FREE_IMAGE_FORMAT format)
{
return LoadEx(filename, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
/// real format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// Load flags can be provided by the flags parameter.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadEx it will be returned in format.
/// </param>