-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPluginTIFF.cpp
More file actions
2675 lines (2151 loc) · 76 KB
/
PluginTIFF.cpp
File metadata and controls
2675 lines (2151 loc) · 76 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
// ==========================================================
// TIFF Loader and Writer
//
// Design and implementation by
// - Floris van den Berg (flvdberg@wxs.nl)
// - Hervé Drolon (drolon@infonie.fr)
// - Markus Loibl (markus.loibl@epost.de)
// - Luca Piergentili (l.pierge@terra.es)
// - Detlev Vendt (detlev.vendt@brillit.de)
// - Mihail Naydenov (mnaydenov@users.sourceforge.net)
//
// 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!
// ==========================================================
#ifdef _MSC_VER
#pragma warning (disable : 4786) // identifier was truncated to 'number' characters
#endif
#ifdef unix
#undef unix
#endif
#ifdef __unix
#undef __unix
#endif
#include "FreeImage.h"
#include "Utilities.h"
#include "../LibTIFF4/tiffiop.h"
#include "../Metadata/FreeImageTag.h"
#include "../OpenEXR/Half/half.h"
#include "FreeImageIO.h"
#include "PSDParser.h"
// --------------------------------------------------------------------------
// GeoTIFF profile (see XTIFF.cpp)
// --------------------------------------------------------------------------
void XTIFFInitialize();
BOOL tiff_read_geotiff_profile(TIFF *tif, FIBITMAP *dib);
BOOL tiff_write_geotiff_profile(TIFF *tif, FIBITMAP *dib);
// --------------------------------------------------------------------------
// TIFF Exif profile (see XTIFF.cpp)
// ----------------------------------------------------------
BOOL tiff_read_exif_tags(TIFF *tif, TagLib::MDMODEL md_model, FIBITMAP *dib);
BOOL tiff_write_exif_tags(TIFF *tif, TagLib::MDMODEL md_model, FIBITMAP *dib);
// --------------------------------------------------------------------------
// LogLuv conversion functions interface (see TIFFLogLuv.cpp)
// --------------------------------------------------------------------------
void tiff_ConvertLineXYZToRGB(BYTE *target, BYTE *source, double stonits, int width_in_pixels);
void tiff_ConvertLineRGBToXYZ(BYTE *target, BYTE *source, int width_in_pixels);
// ----------------------------------------------------------
/** Supported loading methods */
typedef enum {
LoadAsRBGA = 0,
LoadAsCMYK = 1,
LoadAs8BitTrns = 2,
LoadAsGenericStrip = 3,
LoadAsTiled = 4,
LoadAsLogLuv = 5,
LoadAsHalfFloat = 6
} TIFFLoadMethod;
// ----------------------------------------------------------
// local prototypes
// ----------------------------------------------------------
static tmsize_t _tiffReadProc(thandle_t handle, void* buf, tmsize_t size);
static tmsize_t _tiffWriteProc(thandle_t handle, void* buf, tmsize_t size);
static toff_t _tiffSeekProc(thandle_t handle, toff_t off, int whence);
static int _tiffCloseProc(thandle_t fd);
static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize);
static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size);
static uint16 CheckColormap(int n, uint16* r, uint16* g, uint16* b);
static uint16 GetPhotometric(FIBITMAP *dib);
static void ReadResolution(TIFF *tiff, FIBITMAP *dib);
static void WriteResolution(TIFF *tiff, FIBITMAP *dib);
static void ReadPalette(TIFF *tiff, uint16 photometric, uint16 bitspersample, FIBITMAP *dib);
static FIBITMAP* CreateImageType(BOOL header_only, FREE_IMAGE_TYPE fit, int width, int height, uint16 bitspersample, uint16 samplesperpixel);
static FREE_IMAGE_TYPE ReadImageType(TIFF *tiff, uint16 bitspersample, uint16 samplesperpixel);
static void WriteImageType(TIFF *tiff, FREE_IMAGE_TYPE fit);
static void WriteCompression(TIFF *tiff, uint16 bitspersample, uint16 samplesperpixel, uint16 photometric, int flags);
static BOOL tiff_read_iptc_profile(TIFF *tiff, FIBITMAP *dib);
static BOOL tiff_read_xmp_profile(TIFF *tiff, FIBITMAP *dib);
static BOOL tiff_read_exif_profile(FreeImageIO *io, fi_handle handle, TIFF *tiff, FIBITMAP *dib);
static void ReadMetadata(FreeImageIO *io, fi_handle handle, TIFF *tiff, FIBITMAP *dib);
static BOOL tiff_write_iptc_profile(TIFF *tiff, FIBITMAP *dib);
static BOOL tiff_write_xmp_profile(TIFF *tiff, FIBITMAP *dib);
static void WriteMetadata(TIFF *tiff, FIBITMAP *dib);
static TIFFLoadMethod FindLoadMethod(TIFF *tif, uint16 photometric, uint16 bitspersample, uint16 samplesperpixel, FREE_IMAGE_TYPE image_type, int flags);
static void ReadThumbnail(FreeImageIO *io, fi_handle handle, void *data, TIFF *tiff, FIBITMAP *dib);
// ==========================================================
// Plugin Interface
// ==========================================================
static int s_format_id;
typedef struct {
FreeImageIO *io;
fi_handle handle;
TIFF *tif;
} fi_TIFFIO;
// ----------------------------------------------------------
// libtiff interface
// ----------------------------------------------------------
static tmsize_t
_tiffReadProc(thandle_t handle, void *buf, tmsize_t size) {
fi_TIFFIO *fio = (fi_TIFFIO*)handle;
return fio->io->read_proc(buf, (unsigned)size, 1, fio->handle) * size;
}
static tmsize_t
_tiffWriteProc(thandle_t handle, void *buf, tmsize_t size) {
fi_TIFFIO *fio = (fi_TIFFIO*)handle;
return fio->io->write_proc(buf, (unsigned)size, 1, fio->handle) * size;
}
static toff_t
_tiffSeekProc(thandle_t handle, toff_t off, int whence) {
fi_TIFFIO *fio = (fi_TIFFIO*)handle;
fio->io->seek_proc(fio->handle, (long)off, whence);
return fio->io->tell_proc(fio->handle);
}
static int
_tiffCloseProc(thandle_t fd) {
return 0;
}
#include <sys/stat.h>
static toff_t
_tiffSizeProc(thandle_t handle) {
fi_TIFFIO *fio = (fi_TIFFIO*)handle;
long currPos = fio->io->tell_proc(fio->handle);
fio->io->seek_proc(fio->handle, 0, SEEK_END);
long fileSize = fio->io->tell_proc(fio->handle);
fio->io->seek_proc(fio->handle, currPos, SEEK_SET);
return fileSize;
}
static int
_tiffMapProc(thandle_t, void** base, toff_t* size) {
return 0;
}
static void
_tiffUnmapProc(thandle_t, void* base, toff_t size) {
}
/**
Open a TIFF file descriptor for reading or writing
@param handle File handle
@param name Name of the file handle
@param mode Specifies if the file is to be opened for reading ("r") or writing ("w")
*/
TIFF *
TIFFFdOpen(thandle_t handle, const char *name, const char *mode) {
TIFF *tif;
// Open the file; the callback will set everything up
tif = TIFFClientOpen(name, mode, handle,
_tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc,
_tiffSizeProc, _tiffMapProc, _tiffUnmapProc);
return tif;
}
/**
Open a TIFF file for reading or writing
@param name
@param mode
*/
TIFF*
TIFFOpen(const char* name, const char* mode) {
return 0;
}
// ----------------------------------------------------------
// TIFF library FreeImage-specific routines.
// ----------------------------------------------------------
void*
_TIFFmalloc(tmsize_t s) {
return malloc(s);
}
void*
_TIFFcalloc(tmsize_t nmemb, tmsize_t siz) {
if (nmemb == 0 || siz == 0) {
return ((void *)NULL);
}
return calloc((size_t)nmemb, (size_t)siz);
}
void
_TIFFfree(void *p) {
free(p);
}
void*
_TIFFrealloc(void* p, tmsize_t s) {
return realloc(p, s);
}
void
_TIFFmemset(void* p, int v, tmsize_t c) {
memset(p, v, (size_t) c);
}
void
_TIFFmemcpy(void* d, const void* s, tmsize_t c) {
memcpy(d, s, (size_t) c);
}
int
_TIFFmemcmp(const void* p1, const void* p2, tmsize_t c) {
return (memcmp(p1, p2, (size_t) c));
}
// ----------------------------------------------------------
// in FreeImage warnings and errors are disabled
// ----------------------------------------------------------
static void
msdosWarningHandler(const char* module, const char* fmt, va_list ap) {
}
TIFFErrorHandler _TIFFwarningHandler = msdosWarningHandler;
static void
msdosErrorHandler(const char* module, const char* fmt, va_list ap) {
// use this for diagnostic only (do not use otherwise, even in DEBUG mode)
/*
if (module != NULL) {
char msg[1024];
vsprintf(msg, fmt, ap);
FreeImage_OutputMessageProc(s_format_id, "%s: %s", module, msg);
}
*/
}
TIFFErrorHandler _TIFFerrorHandler = msdosErrorHandler;
// ----------------------------------------------------------
#define CVT(x) (((x) * 255L) / ((1L<<16)-1))
#define SCALE(x) (((x)*((1L<<16)-1))/255)
// ==========================================================
// Internal functions
// ==========================================================
static uint16
CheckColormap(int n, uint16* r, uint16* g, uint16* b) {
while (n-- > 0) {
if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) {
return 16;
}
}
return 8;
}
/**
Get the TIFFTAG_PHOTOMETRIC value from the dib
*/
static uint16
GetPhotometric(FIBITMAP *dib) {
FREE_IMAGE_COLOR_TYPE color_type = FreeImage_GetColorType(dib);
switch(color_type) {
case FIC_MINISWHITE: // min value is white
return PHOTOMETRIC_MINISWHITE;
case FIC_MINISBLACK: // min value is black
return PHOTOMETRIC_MINISBLACK;
case FIC_PALETTE: // color map indexed
return PHOTOMETRIC_PALETTE;
case FIC_RGB: // RGB color model
case FIC_RGBALPHA: // RGB color model with alpha channel
return PHOTOMETRIC_RGB;
case FIC_CMYK: // CMYK color model
return PHOTOMETRIC_RGB; // default to RGB unless the save flag is set to TIFF_CMYK
default:
return PHOTOMETRIC_MINISBLACK;
}
}
/**
Get the resolution from the TIFF and fill the dib with universal units
*/
static void
ReadResolution(TIFF *tiff, FIBITMAP *dib) {
float fResX = 300.0;
float fResY = 300.0;
uint16 resUnit = RESUNIT_INCH;
TIFFGetField(tiff, TIFFTAG_RESOLUTIONUNIT, &resUnit);
TIFFGetField(tiff, TIFFTAG_XRESOLUTION, &fResX);
TIFFGetField(tiff, TIFFTAG_YRESOLUTION, &fResY);
// If we don't have a valid resolution unit and valid resolution is specified then assume inch
if (resUnit == RESUNIT_NONE && fResX > 0.0 && fResY > 0.0) {
resUnit = RESUNIT_INCH;
}
if (resUnit == RESUNIT_INCH) {
FreeImage_SetDotsPerMeterX(dib, (unsigned) (fResX/0.0254000 + 0.5));
FreeImage_SetDotsPerMeterY(dib, (unsigned) (fResY/0.0254000 + 0.5));
} else if(resUnit == RESUNIT_CENTIMETER) {
FreeImage_SetDotsPerMeterX(dib, (unsigned) (fResX*100.0 + 0.5));
FreeImage_SetDotsPerMeterY(dib, (unsigned) (fResY*100.0 + 0.5));
}
}
/**
Set the resolution to the TIFF using english units
*/
static void
WriteResolution(TIFF *tiff, FIBITMAP *dib) {
double res;
TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
res = (unsigned long) (0.5 + 0.0254 * FreeImage_GetDotsPerMeterX(dib));
TIFFSetField(tiff, TIFFTAG_XRESOLUTION, res);
res = (unsigned long) (0.5 + 0.0254 * FreeImage_GetDotsPerMeterY(dib));
TIFFSetField(tiff, TIFFTAG_YRESOLUTION, res);
}
/**
Fill the dib palette according to the TIFF photometric
*/
static void
ReadPalette(TIFF *tiff, uint16 photometric, uint16 bitspersample, FIBITMAP *dib) {
RGBQUAD *pal = FreeImage_GetPalette(dib);
switch(photometric) {
case PHOTOMETRIC_MINISBLACK: // bitmap and greyscale image types
case PHOTOMETRIC_MINISWHITE:
// Monochrome image
if (bitspersample == 1) {
if (photometric == PHOTOMETRIC_MINISWHITE) {
pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 255;
pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 0;
} else {
pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 0;
pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255;
}
} else if ((bitspersample == 4) ||(bitspersample == 8)) {
// need to build the scale for greyscale images
int ncolors = FreeImage_GetColorsUsed(dib);
if (photometric == PHOTOMETRIC_MINISBLACK) {
for (int i = 0; i < ncolors; i++) {
pal[i].rgbRed =
pal[i].rgbGreen =
pal[i].rgbBlue = (BYTE)(i*(255/(ncolors-1)));
}
} else {
for (int i = 0; i < ncolors; i++) {
pal[i].rgbRed =
pal[i].rgbGreen =
pal[i].rgbBlue = (BYTE)(255-i*(255/(ncolors-1)));
}
}
}
break;
case PHOTOMETRIC_PALETTE: // color map indexed
uint16 *red;
uint16 *green;
uint16 *blue;
TIFFGetField(tiff, TIFFTAG_COLORMAP, &red, &green, &blue);
// load the palette in the DIB
if (CheckColormap(1<<bitspersample, red, green, blue) == 16) {
for (int i = (1 << bitspersample) - 1; i >= 0; i--) {
pal[i].rgbRed =(BYTE) CVT(red[i]);
pal[i].rgbGreen = (BYTE) CVT(green[i]);
pal[i].rgbBlue = (BYTE) CVT(blue[i]);
}
} else {
for (int i = (1 << bitspersample) - 1; i >= 0; i--) {
pal[i].rgbRed = (BYTE) red[i];
pal[i].rgbGreen = (BYTE) green[i];
pal[i].rgbBlue = (BYTE) blue[i];
}
}
break;
}
}
/**
Allocate a FIBITMAP
@param header_only If TRUE, allocate a 'header only' FIBITMAP, otherwise allocate a full FIBITMAP
@param fit Image type
@param width Image width in pixels
@param height Image height in pixels
@param bitspersample # bits per sample
@param samplesperpixel # samples per pixel
@return Returns the allocated image if successful, returns NULL otherwise
*/
static FIBITMAP*
CreateImageType(BOOL header_only, FREE_IMAGE_TYPE fit, int width, int height, uint16 bitspersample, uint16 samplesperpixel) {
FIBITMAP *dib = NULL;
if((width < 0) || (height < 0)) {
// check for malicious images
return NULL;
}
int bpp = bitspersample * samplesperpixel;
if(fit == FIT_BITMAP) {
// standard bitmap type
if(bpp == 16) {
if((samplesperpixel == 2) && (bitspersample == 8)) {
// 8-bit indexed + 8-bit alpha channel -> convert to 8-bit transparent
dib = FreeImage_AllocateHeader(header_only, width, height, 8);
} else {
// 16-bit RGB -> expect it to be 565
dib = FreeImage_AllocateHeader(header_only, width, height, bpp, FI16_565_RED_MASK, FI16_565_GREEN_MASK, FI16_565_BLUE_MASK);
}
}
else {
dib = FreeImage_AllocateHeader(header_only, width, height, MIN(bpp, 32), FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
}
} else {
// other bitmap types
dib = FreeImage_AllocateHeaderT(header_only, fit, width, height, bpp);
}
return dib;
}
/**
Read the TIFFTAG_SAMPLEFORMAT tag and convert to FREE_IMAGE_TYPE
@param tiff LibTIFF TIFF Handle
@param bitspersample # bit per sample
@param samplesperpixel # samples per pixel
@return Returns the image type as a FREE_IMAGE_TYPE value
*/
static FREE_IMAGE_TYPE
ReadImageType(TIFF *tiff, uint16 bitspersample, uint16 samplesperpixel) {
uint16 sampleformat = 0;
FREE_IMAGE_TYPE fit = FIT_BITMAP ;
uint16 bpp = bitspersample * samplesperpixel;
// try the sampleformat tag
if(TIFFGetField(tiff, TIFFTAG_SAMPLEFORMAT, &sampleformat)) {
switch (sampleformat) {
case SAMPLEFORMAT_UINT:
switch (bpp) {
case 1:
case 4:
case 8:
case 24:
fit = FIT_BITMAP;
break;
case 16:
// 8-bit + alpha or 16-bit greyscale
if(samplesperpixel == 2) {
fit = FIT_BITMAP;
} else {
fit = FIT_UINT16;
}
break;
case 32:
if(samplesperpixel == 4) {
fit = FIT_BITMAP;
} else {
fit = FIT_UINT32;
}
break;
case 48:
if(samplesperpixel == 3) {
fit = FIT_RGB16;
}
break;
case 64:
if(samplesperpixel == 4) {
fit = FIT_RGBA16;
}
break;
}
break;
case SAMPLEFORMAT_INT:
switch (bpp) {
case 16:
if(samplesperpixel == 3) {
fit = FIT_BITMAP;
} else {
fit = FIT_INT16;
}
break;
case 32:
fit = FIT_INT32;
break;
}
break;
case SAMPLEFORMAT_IEEEFP:
switch (bpp) {
case 32:
fit = FIT_FLOAT;
break;
case 48:
// 3 x half float => convert to RGBF
if((samplesperpixel == 3) && (bitspersample == 16)) {
fit = FIT_RGBF;
}
break;
case 64:
if(samplesperpixel == 2) {
fit = FIT_FLOAT;
} else {
fit = FIT_DOUBLE;
}
break;
case 96:
fit = FIT_RGBF;
break;
default:
if(bpp >= 128) {
fit = FIT_RGBAF;
}
break;
}
break;
case SAMPLEFORMAT_COMPLEXIEEEFP:
switch (bpp) {
case 64:
break;
case 128:
fit = FIT_COMPLEX;
break;
}
break;
}
}
// no sampleformat tag : assume SAMPLEFORMAT_UINT
else {
if(samplesperpixel == 1) {
switch (bpp) {
case 16:
fit = FIT_UINT16;
break;
case 32:
fit = FIT_UINT32;
break;
}
}
else if(samplesperpixel == 3) {
if(bpp == 48) fit = FIT_RGB16;
}
else if(samplesperpixel >= 4) {
if(bitspersample == 16) {
fit = FIT_RGBA16;
}
}
}
return fit;
}
/**
Convert FREE_IMAGE_TYPE and write TIFFTAG_SAMPLEFORMAT
@param tiff LibTIFF TIFF Handle
@param fit Image type as a FREE_IMAGE_TYPE value
*/
static void
WriteImageType(TIFF *tiff, FREE_IMAGE_TYPE fit) {
switch(fit) {
case FIT_BITMAP: // standard image: 1-, 4-, 8-, 16-, 24-, 32-bit
case FIT_UINT16: // array of unsigned short : unsigned 16-bit
case FIT_UINT32: // array of unsigned long : unsigned 32-bit
case FIT_RGB16: // 48-bit RGB image : 3 x 16-bit
case FIT_RGBA16: // 64-bit RGBA image : 4 x 16-bit
TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case FIT_INT16: // array of short : signed 16-bit
case FIT_INT32: // array of long : signed 32-bit
TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case FIT_FLOAT: // array of float : 32-bit
case FIT_DOUBLE: // array of double : 64-bit
case FIT_RGBF: // 96-bit RGB float image : 3 x 32-bit IEEE floating point
case FIT_RGBAF: // 128-bit RGBA float image : 4 x 32-bit IEEE floating point
TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
case FIT_COMPLEX: // array of COMPLEX : 2 x 64-bit
TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_COMPLEXIEEEFP);
break;
}
}
/**
Select the compression algorithm
@param tiff LibTIFF TIFF Handle
@param
*/
static void
WriteCompression(TIFF *tiff, uint16 bitspersample, uint16 samplesperpixel, uint16 photometric, int flags) {
uint16 compression;
uint16 bitsperpixel = bitspersample * samplesperpixel;
if(photometric == PHOTOMETRIC_LOGLUV) {
compression = COMPRESSION_SGILOG;
} else if ((flags & TIFF_PACKBITS) == TIFF_PACKBITS) {
compression = COMPRESSION_PACKBITS;
} else if ((flags & TIFF_DEFLATE) == TIFF_DEFLATE) {
compression = COMPRESSION_DEFLATE;
} else if ((flags & TIFF_ADOBE_DEFLATE) == TIFF_ADOBE_DEFLATE) {
compression = COMPRESSION_ADOBE_DEFLATE;
} else if ((flags & TIFF_NONE) == TIFF_NONE) {
compression = COMPRESSION_NONE;
} else if ((bitsperpixel == 1) && ((flags & TIFF_CCITTFAX3) == TIFF_CCITTFAX3)) {
compression = COMPRESSION_CCITTFAX3;
} else if ((bitsperpixel == 1) && ((flags & TIFF_CCITTFAX4) == TIFF_CCITTFAX4)) {
compression = COMPRESSION_CCITTFAX4;
} else if ((flags & TIFF_LZW) == TIFF_LZW) {
compression = COMPRESSION_LZW;
} else if ((flags & TIFF_JPEG) == TIFF_JPEG) {
if(((bitsperpixel == 8) && (photometric != PHOTOMETRIC_PALETTE)) || (bitsperpixel == 24)) {
compression = COMPRESSION_JPEG;
// RowsPerStrip must be multiple of 8 for JPEG
uint32 rowsperstrip = (uint32) -1;
rowsperstrip = TIFFDefaultStripSize(tiff, rowsperstrip);
rowsperstrip = rowsperstrip + (8 - (rowsperstrip % 8));
// overwrite previous RowsPerStrip
TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
} else {
// default to LZW
compression = COMPRESSION_LZW;
}
}
else {
// default compression scheme
switch(bitsperpixel) {
case 1:
compression = COMPRESSION_CCITTFAX4;
break;
case 4:
case 8:
case 16:
case 24:
case 32:
compression = COMPRESSION_LZW;
break;
case 48:
case 64:
case 96:
case 128:
compression = COMPRESSION_LZW;
break;
default :
compression = COMPRESSION_NONE;
break;
}
}
TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression);
if(compression == COMPRESSION_LZW) {
// This option is only meaningful with LZW compression: a predictor value of 2
// causes each scanline of the output image to undergo horizontal differencing
// before it is encoded; a value of 1 forces each scanline to be encoded without differencing.
// Found on LibTIFF mailing list :
// LZW without differencing works well for 1-bit images, 4-bit grayscale images,
// and many palette-color images. But natural 24-bit color images and some 8-bit
// grayscale images do much better with differencing.
if((bitspersample == 8) || (bitspersample == 16)) {
if ((bitsperpixel >= 8) && (photometric != PHOTOMETRIC_PALETTE)) {
TIFFSetField(tiff, TIFFTAG_PREDICTOR, 2);
} else {
TIFFSetField(tiff, TIFFTAG_PREDICTOR, 1);
}
} else {
TIFFSetField(tiff, TIFFTAG_PREDICTOR, 1);
}
}
else if((compression == COMPRESSION_CCITTFAX3) || (compression == COMPRESSION_CCITTFAX4)) {
uint32 imageLength = 0;
TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &imageLength);
// overwrite previous RowsPerStrip
TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, imageLength);
if(compression == COMPRESSION_CCITTFAX3) {
// try to be compliant with the TIFF Class F specification
// that documents the TIFF tags specific to FAX applications
// see http://palimpsest.stanford.edu/bytopic/imaging/std/tiff-f.html
uint32 group3options = GROUP3OPT_2DENCODING | GROUP3OPT_FILLBITS;
TIFFSetField(tiff, TIFFTAG_GROUP3OPTIONS, group3options); // 2d-encoded, has aligned EOL
TIFFSetField(tiff, TIFFTAG_FILLORDER, FILLORDER_LSB2MSB); // lsb-to-msb fillorder
}
}
}
// ==========================================================
// TIFF metadata routines
// ==========================================================
/**
Read the TIFFTAG_RICHTIFFIPTC tag (IPTC/NAA or Adobe Photoshop profile)
*/
static BOOL
tiff_read_iptc_profile(TIFF *tiff, FIBITMAP *dib) {
BYTE *profile = NULL;
uint32 profile_size = 0;
if(TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC, &profile_size, &profile) == 1) {
if (TIFFIsByteSwapped(tiff) != 0) {
TIFFSwabArrayOfLong((uint32 *) profile, (unsigned long)profile_size);
}
return read_iptc_profile(dib, profile, 4 * profile_size);
}
return FALSE;
}
/**
Read the TIFFTAG_XMLPACKET tag (XMP profile)
@param dib Input FIBITMAP
@param tiff LibTIFF TIFF handle
@return Returns TRUE if successful, FALSE otherwise
*/
static BOOL
tiff_read_xmp_profile(TIFF *tiff, FIBITMAP *dib) {
BYTE *profile = NULL;
uint32 profile_size = 0;
if (TIFFGetField(tiff, TIFFTAG_XMLPACKET, &profile_size, &profile) == 1) {
// create a tag
FITAG *tag = FreeImage_CreateTag();
if(!tag) return FALSE;
FreeImage_SetTagID(tag, TIFFTAG_XMLPACKET); // 700
FreeImage_SetTagKey(tag, g_TagLib_XMPFieldName);
FreeImage_SetTagLength(tag, profile_size);
FreeImage_SetTagCount(tag, profile_size);
FreeImage_SetTagType(tag, FIDT_ASCII);
FreeImage_SetTagValue(tag, profile);
// store the tag
FreeImage_SetMetadata(FIMD_XMP, dib, FreeImage_GetTagKey(tag), tag);
// destroy the tag
FreeImage_DeleteTag(tag);
return TRUE;
}
return FALSE;
}
/**
Read the Exif profile embedded in a TIFF
@param dib Input FIBITMAP
@param tiff LibTIFF TIFF handle
@return Returns TRUE if successful, FALSE otherwise
*/
static BOOL
tiff_read_exif_profile(FreeImageIO *io, fi_handle handle, TIFF *tiff, FIBITMAP *dib) {
BOOL bResult = FALSE;
toff_t exif_offset = 0;
// read EXIF-TIFF tags
bResult = tiff_read_exif_tags(tiff, TagLib::EXIF_MAIN, dib);
// get the IFD offset
if(TIFFGetField(tiff, TIFFTAG_EXIFIFD, &exif_offset)) {
const long tell_pos = io->tell_proc(handle);
const uint16 cur_dir = TIFFCurrentDirectory(tiff);
// read EXIF tags
if (TIFFReadEXIFDirectory(tiff, exif_offset)) {
// read all known exif tags
bResult = tiff_read_exif_tags(tiff, TagLib::EXIF_EXIF, dib);
}
io->seek_proc(handle, tell_pos, SEEK_SET);
TIFFSetDirectory(tiff, cur_dir);
}
return bResult;
}
/**
Read TIFF special profiles
*/
static void
ReadMetadata(FreeImageIO *io, fi_handle handle, TIFF *tiff, FIBITMAP *dib) {
// IPTC/NAA
tiff_read_iptc_profile(tiff, dib);
// Adobe XMP
tiff_read_xmp_profile(tiff, dib);
// GeoTIFF
tiff_read_geotiff_profile(tiff, dib);
// Exif-TIFF
tiff_read_exif_profile(io, handle, tiff, dib);
}
// ----------------------------------------------------------
/**
Write the TIFFTAG_RICHTIFFIPTC tag (IPTC/NAA or Adobe Photoshop profile)
*/
static BOOL
tiff_write_iptc_profile(TIFF *tiff, FIBITMAP *dib) {
if(FreeImage_GetMetadataCount(FIMD_IPTC, dib)) {
BYTE *profile = NULL;
uint32 profile_size = 0;
// create a binary profile
if(write_iptc_profile(dib, &profile, &profile_size)) {
uint32 iptc_size = profile_size;
iptc_size += (4-(iptc_size & 0x03)); // Round up for long word alignment
BYTE *iptc_profile = (BYTE*)malloc(iptc_size);
if(!iptc_profile) {
free(profile);
return FALSE;
}
memset(iptc_profile, 0, iptc_size);
memcpy(iptc_profile, profile, profile_size);
if (TIFFIsByteSwapped(tiff)) {
TIFFSwabArrayOfLong((uint32 *) iptc_profile, (unsigned long)iptc_size/4);
}
// Tag is type TIFF_LONG so byte length is divided by four
TIFFSetField(tiff, TIFFTAG_RICHTIFFIPTC, iptc_size/4, iptc_profile);
// release the profile data
free(iptc_profile);
free(profile);
return TRUE;
}
}
return FALSE;
}
/**
Write the TIFFTAG_XMLPACKET tag (XMP profile)
@param dib Input FIBITMAP
@param tiff LibTIFF TIFF handle
@return Returns TRUE if successful, FALSE otherwise
*/
static BOOL
tiff_write_xmp_profile(TIFF *tiff, FIBITMAP *dib) {
FITAG *tag_xmp = NULL;
FreeImage_GetMetadata(FIMD_XMP, dib, g_TagLib_XMPFieldName, &tag_xmp);
if(tag_xmp && (NULL != FreeImage_GetTagValue(tag_xmp))) {
TIFFSetField(tiff, TIFFTAG_XMLPACKET, (uint32)FreeImage_GetTagLength(tag_xmp), (BYTE*)FreeImage_GetTagValue(tag_xmp));
return TRUE;
}
return FALSE;
}
/**
Write the Exif profile to TIFF
@param dib Input FIBITMAP
@param tiff LibTIFF TIFF handle
@return Returns TRUE if successful, FALSE otherwise
*/
static BOOL
tiff_write_exif_profile(TIFF *tiff, FIBITMAP *dib) {
BOOL bResult = FALSE;
// write EXIF_MAIN tags, EXIF_EXIF not supported yet
bResult = tiff_write_exif_tags(tiff, TagLib::EXIF_MAIN, dib);
return bResult;
}
/**
Write TIFF special profiles
*/
static void
WriteMetadata(TIFF *tiff, FIBITMAP *dib) {
// IPTC
tiff_write_iptc_profile(tiff, dib);
// Adobe XMP
tiff_write_xmp_profile(tiff, dib);
// EXIF_MAIN tags
tiff_write_exif_profile(tiff, dib);
// GeoTIFF tags
tiff_write_geotiff_profile(tiff, dib);
}
// ==========================================================
// Plugin Implementation
// ==========================================================
static const char * DLL_CALLCONV
Format() {
return "TIFF";
}
static const char * DLL_CALLCONV
Description() {
return "Tagged Image File Format";
}
static const char * DLL_CALLCONV
Extension() {
return "tif,tiff";
}
static const char * DLL_CALLCONV
RegExpr() {
return "^[MI][MI][\\x01*][\\x01*]";
}
static const char * DLL_CALLCONV
MimeType() {
return "image/tiff";
}
static BOOL DLL_CALLCONV
Validate(FreeImageIO *io, fi_handle handle) {
BYTE tiff_id1[] = { 0x49, 0x49, 0x2A, 0x00 }; // Classic TIFF, little-endian
BYTE tiff_id2[] = { 0x4D, 0x4D, 0x00, 0x2A }; // Classic TIFF, big-endian
BYTE tiff_id3[] = { 0x49, 0x49, 0x2B, 0x00 }; // Big TIFF, little-endian
BYTE tiff_id4[] = { 0x4D, 0x4D, 0x00, 0x2B }; // Big TIFF, big-endian
BYTE signature[4] = { 0, 0, 0, 0 };
io->read_proc(signature, 1, 4, handle);
if(memcmp(tiff_id1, signature, 4) == 0)
return TRUE;
if(memcmp(tiff_id2, signature, 4) == 0)
return TRUE;
if(memcmp(tiff_id3, signature, 4) == 0)