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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
|
// ==========================================================
// 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 interface (see XTIFF.cpp)
// ----------------------------------------------------------
// Extended TIFF Directory GEO Tag Support
void XTIFFInitialize();
// GeoTIFF profile
void tiff_read_geotiff_profile(TIFF *tif, FIBITMAP *dib);
void tiff_write_geotiff_profile(TIFF *tif, FIBITMAP *dib);
// ----------------------------------------------------------
// exif interface (see XTIFF.cpp)
// ----------------------------------------------------------
// TIFF Exif profile
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(TIFF *tiff, FIBITMAP *dib);
static void ReadMetadata(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, 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, 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, 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;
// Set up the callback for extended TIFF directory tag support
// (see XTIFF.cpp)
XTIFFInitialize();
// Open the file; the callback will set everything up
tif = TIFFClientOpen(name, mode, handle,
_tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc,
_tiffSizeProc, _tiffMapProc, _tiffUnmapProc);
// Warning: tif_fd is declared as 'int' currently (see libTIFF),
// may result in incorrect file pointers inside libTIFF on
// 64bit machines (sizeof(int) != sizeof(long)).
// Needs to be fixed within libTIFF.
if (tif) {
tif->tif_fd = (long)handle;
}
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
_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) {
// 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(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)) {
// read EXIF tags
if (!TIFFReadEXIFDirectory(tiff, exif_offset)) {
return FALSE;
}
// read all known exif tags
bResult = tiff_read_exif_tags(tiff, TagLib::EXIF_EXIF, dib);
}
return bResult;
}
/**
Read TIFF special profiles
*/
static void
ReadMetadata(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(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;
uint32 exif_offset = 0;
// 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 };
BYTE tiff_id2[] = { 0x4D, 0x4D, 0x00, 0x2A };
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;
return FALSE;
}
static BOOL DLL_CALLCONV
SupportsExportDepth(int depth) {
return (
(depth == 1) ||
(depth == 4) ||
(depth == 8) ||
(depth == 24) ||
(depth == 32)
);
}
static BOOL DLL_CALLCONV
SupportsExportType(FREE_IMAGE_TYPE type) {
return (
(type == FIT_BITMAP) ||
(type == FIT_UINT16) ||
(type == FIT_INT16) ||
(type == FIT_UINT32) ||
(type == FIT_INT32) ||
(type == FIT_FLOAT) ||
(type == FIT_DOUBLE) ||
(type == FIT_COMPLEX) ||
(type == FIT_RGB16) ||
(type == FIT_RGBA16) ||
(type == FIT_RGBF) ||
(type == FIT_RGBAF)
);
}
static BOOL DLL_CALLCONV
SupportsICCProfiles() {
return TRUE;
}
static BOOL DLL_CALLCONV
SupportsNoPixels() {
return TRUE;
}
// ----------------------------------------------------------
static void * DLL_CALLCONV
Open(FreeImageIO *io, fi_handle handle, BOOL read) {
// wrapper for TIFF I/O
fi_TIFFIO *fio = (fi_TIFFIO*)malloc(sizeof(fi_TIFFIO));
if (!fio) return NULL;
fio->io = io;
fio->handle = handle;
if (read) {
fio->tif = TIFFFdOpen((thandle_t)fio, "", "r");
} else {
fio->tif = TIFFFdOpen((thandle_t)fio, "", "w");
}
if(fio->tif == NULL) {
free(fio);
FreeImage_OutputMessageProc(s_format_id, "Error while opening TIFF: data is invalid");
return NULL;
}
return fio;
}
static void DLL_CALLCONV
Close(FreeImageIO *io, fi_handle handle, void *data) {
if(data) {
fi_TIFFIO *fio = (fi_TIFFIO*)data;
TIFFClose(fio->tif);
free(fio);
}
}
// ----------------------------------------------------------
static int DLL_CALLCONV
PageCount(FreeImageIO *io, fi_handle handle, void *data) {
if(data) {
fi_TIFFIO *fio = (fi_TIFFIO*)data;
TIFF *tif = (TIFF *)fio->tif;
int nr_ifd = 0;
do {
nr_ifd++;
} while (TIFFReadDirectory(tif));
return nr_ifd;
}
return 0;
}
// ----------------------------------------------------------
/**
check for uncommon bitspersample values (e.g. 10, 12, ...)
@param photometric TIFFTAG_PHOTOMETRIC tiff tag
@param bitspersample TIFFTAG_BITSPERSAMPLE tiff tag
@param samplesperpixel TIFFTAG_SAMPLESPERPIXEL tiff tag
@return Returns FALSE if a uncommon bit-depth is encountered, returns TRUE otherwise
*/
static BOOL
IsValidBitsPerSample(uint16 photometric, uint16 bitspersample, uint16 samplesperpixel) {
switch(bitspersample) {
case 1:
case 4:
if ((photometric == PHOTOMETRIC_MINISWHITE) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_PALETTE)) {
return TRUE;
} else {
return FALSE;
}
break;
case 8:
return TRUE;
case 16:
if(photometric != PHOTOMETRIC_PALETTE) {
return TRUE;
} else {
return FALSE;
}
break;
case 32:
return TRUE;
case 64:
case 128:
if(photometric == PHOTOMETRIC_MINISBLACK) {
return TRUE;
} else {
return FALSE;
}
break;
default:
return FALSE;
}
}
static TIFFLoadMethod
FindLoadMethod(TIFF *tif, FREE_IMAGE_TYPE image_type, int flags) {
uint16 bitspersample = (uint16)-1;
uint16 samplesperpixel = (uint16)-1;
uint16 photometric = (uint16)-1;
uint16 planar_config = (uint16)-1;
TIFFLoadMethod loadMethod = LoadAsGenericStrip;
TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planar_config);
BOOL bIsTiled = (TIFFIsTiled(tif) == 0) ? FALSE:TRUE;
switch(photometric) {
// convert to 24 or 32 bits RGB if the image is full color
case PHOTOMETRIC_RGB:
if ((image_type == FIT_RGB16) || (image_type == FIT_RGBA16)) {
// load 48-bit RGB and 64-bit RGBA without conversion
loadMethod = LoadAsGenericStrip;
}
else if(image_type == FIT_RGBF) {
if ((samplesperpixel == 3) && (bitspersample == 16)) {
// load 3 x 16-bit half as RGBF
loadMethod = LoadAsHalfFloat;
}
}
break;
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_ICCLAB:
case PHOTOMETRIC_ITULAB:
loadMethod = LoadAsRBGA;
break;
case PHOTOMETRIC_LOGLUV:
loadMethod = LoadAsLogLuv;
break;
case PHOTOMETRIC_SEPARATED:
// if image is PHOTOMETRIC_SEPARATED _and_ comes with an ICC profile,
// then the image should preserve its original (CMYK) colour model and
// should be read as CMYK (to keep the match of pixel and profile and
// to avoid multiple conversions. Conversion can be done by changing
// the profile from it's original CMYK to an RGB profile with an
// apropriate color management system. Works with non-tiled TIFFs.
if (!bIsTiled) {
loadMethod = LoadAsCMYK;
}
break;
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
case PHOTOMETRIC_PALETTE:
// When samplesperpixel = 2 and bitspersample = 8, set the image as a
// 8-bit indexed image + 8-bit alpha layer image
// and convert to a 8-bit image with a transparency table
if ((samplesperpixel > 1) && (bitspersample == 8)) {
loadMethod = LoadAs8BitTrns;
} else {
loadMethod = LoadAsGenericStrip;
}
break;
default:
loadMethod = LoadAsGenericStrip;
break;
}
if ((loadMethod == LoadAsGenericStrip) && bIsTiled) {
loadMethod = LoadAsTiled;
}
return loadMethod;
}
// ==========================================================
// TIFF thumbnail routines
// ==========================================================
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data);
/**
Read embedded thumbnail
*/
static void
ReadThumbnail(FreeImageIO *io, fi_handle handle, void *data, TIFF *tiff, FIBITMAP *dib) {
FIBITMAP* thumbnail = NULL;
// read exif thumbnail (IFD 1) ...
uint32 exif_offset = 0;
if(TIFFGetField(tiff, TIFFTAG_EXIFIFD, &exif_offset)) {
if(TIFFLastDirectory(tiff) != 0) {
// save current position
long tell_pos = io->tell_proc(handle);
uint16 cur_dir = TIFFCurrentDirectory(tiff);
// load the thumbnail
int page = 1;
int flags = TIFF_DEFAULT;
thumbnail = Load(io, handle, page, flags, data);
// store the thumbnail (remember to release it later ...)
FreeImage_SetThumbnail(dib, thumbnail);
// restore current position
io->seek_proc(handle, tell_pos, SEEK_SET);
TIFFSetDirectory(tiff, cur_dir);
}
}
// ... or read the first subIFD
if (!thumbnail) {
uint16 subIFD_count = 0;
uint64* subIFD_offsets = NULL;
// ### Theoretically this should also read the first subIFD from a Photoshop-created file with "pyramid".
// It does not however - the tag is there (using Tag Viewer app) but libtiff refuses to read it
if(TIFFGetField(tiff, TIFFTAG_SUBIFD, &subIFD_count, &subIFD_offsets)) {
if(subIFD_count > 0) {
// save current position
long tell_pos = io->tell_proc(handle);
uint16 cur_dir = TIFFCurrentDirectory(tiff);
if(TIFFSetSubDirectory(tiff, subIFD_offsets[0])) {
// load the thumbnail
int page = -1;
int flags = TIFF_DEFAULT;
thumbnail = Load(io, handle, page, flags, data);
// store the thumbnail (remember to release it later ...)
FreeImage_SetThumbnail(dib, thumbnail);
}
// restore current position
io->seek_proc(handle, tell_pos, SEEK_SET);
TIFFSetDirectory(tiff, cur_dir);
}
}
}
// ... or read Photoshop thumbnail
if (!thumbnail) {
uint32 ps_size = 0;
void *ps_data = NULL;
if(TIFFGetField(tiff, TIFFTAG_PHOTOSHOP, &ps_size, &ps_data)) {
FIMEMORY *handle = FreeImage_OpenMemory((BYTE*)ps_data, ps_size);
FreeImageIO io;
SetMemoryIO(&io);
psdParser parser;
parser.ReadImageResources(&io, handle, ps_size);
FreeImage_SetThumbnail(dib, parser.GetThumbnail());
FreeImage_CloseMemory(handle);
}
}
// release thumbnail
FreeImage_Unload(thumbnail);
}
// --------------------------------------------------------------------------
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
if (!handle || !data ) {
return NULL;
}
TIFF *tif = NULL;
uint32 height = 0;
uint32 width = 0;
uint16 bitspersample = 1;
uint16 samplesperpixel = 1;
uint32 rowsperstrip = (uint32)-1;
uint16 photometric = PHOTOMETRIC_MINISWHITE;
uint16 compression = (uint16)-1;
uint16 planar_config;
FIBITMAP *dib = NULL;
uint32 iccSize = 0; // ICC profile length
void *iccBuf = NULL; // ICC profile data
const BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;
try {
fi_TIFFIO *fio = (fi_TIFFIO*)data;
tif = fio->tif;
if (page != -1) {
if (!tif || !TIFFSetDirectory(tif, (uint16)page)) {
throw "Error encountered while opening TIFF file";
}
}
const BOOL asCMYK = (flags & TIFF_CMYK) == TIFF_CMYK;
// first, get the photometric, the compression and basic metadata
// ---------------------------------------------------------------------------------
TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric);
TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
// check for HDR formats
// ---------------------------------------------------------------------------------
if(photometric == PHOTOMETRIC_LOGLUV) {
// check the compression
if(compression != COMPRESSION_SGILOG && compression != COMPRESSION_SGILOG24) {
throw "Only support SGILOG compressed LogLuv data";
}
// set decoder to output in IEEE 32-bit float XYZ values
TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_FLOAT);
}
// ---------------------------------------------------------------------------------
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
TIFFGetField(tif, TIFFTAG_ICCPROFILE, &iccSize, &iccBuf);
TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planar_config);
// check for unsupported formats
// ---------------------------------------------------------------------------------
if(IsValidBitsPerSample(photometric, bitspersample, samplesperpixel) == FALSE) {
FreeImage_OutputMessageProc(s_format_id,
"Unable to handle this format: bitspersample = %d, samplesperpixel = %d, photometric = %d",
(int)bitspersample, (int)samplesperpixel, (int)photometric);
throw (char*)NULL;
}
// ---------------------------------------------------------------------------------
// get image data type
FREE_IMAGE_TYPE image_type = ReadImageType(tif, bitspersample, samplesperpixel);
// get the most appropriate loading method
TIFFLoadMethod loadMethod = FindLoadMethod(tif, image_type, flags);
// ---------------------------------------------------------------------------------
if(loadMethod == LoadAsRBGA) {
// ---------------------------------------------------------------------------------
// RGB[A] loading using the TIFFReadRGBAImage() API
// ---------------------------------------------------------------------------------
BOOL has_alpha = FALSE;
// Read the whole image into one big RGBA buffer and then
// convert it to a DIB. This is using the traditional
// TIFFReadRGBAImage() API that we trust.
uint32 *raster = NULL;
if (!header_only) {
raster = (uint32*)_TIFFmalloc(width * height * sizeof(uint32));
if (raster == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// read the image in one chunk into an RGBA array
if (!TIFFReadRGBAImage(tif, width, height, raster, 1)) {
_TIFFfree(raster);
throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
}
}
// TIFFReadRGBAImage always deliveres 3 or 4 samples per pixel images
// (RGB or RGBA, see below). Cut-off possibly present channels (additional
// alpha channels) from e.g. Photoshop. Any CMYK(A..) is now treated as RGB,
// any additional alpha channel on RGB(AA..) is lost on conversion to RGB(A)
if(samplesperpixel > 4) { // TODO Write to Extra Channels
FreeImage_OutputMessageProc(s_format_id, "Warning: %d additional alpha channel(s) ignored", samplesperpixel-4);
samplesperpixel = 4;
}
// create a new DIB (take care of different samples-per-pixel in case
// of converted CMYK image (RGB conversion is on sample per pixel less)
if (photometric == PHOTOMETRIC_SEPARATED && samplesperpixel == 4) {
samplesperpixel = 3;
}
dib = CreateImageType(header_only, image_type, width, height, bitspersample, samplesperpixel);
if (dib == NULL) {
// free the raster pointer and output an error if allocation failed
if(raster) {
_TIFFfree(raster);
}
throw FI_MSG_ERROR_DIB_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
if (!header_only) {
// read the raster lines and save them in the DIB
// with RGB mode, we have to change the order of the 3 samples RGB
// We use macros for extracting components from the packed ABGR
// form returned by TIFFReadRGBAImage.
uint32 *row = &raster[0];
if (samplesperpixel == 4) {
// 32-bit RGBA
for (uint32 y = 0; y < height; y++) {
BYTE *bits = FreeImage_GetScanLine(dib, y);
for (uint32 x = 0; x < width; x++) {
bits[FI_RGBA_BLUE] = (BYTE)TIFFGetB(row[x]);
bits[FI_RGBA_GREEN] = (BYTE)TIFFGetG(row[x]);
bits[FI_RGBA_RED] = (BYTE)TIFFGetR(row[x]);
bits[FI_RGBA_ALPHA] = (BYTE)TIFFGetA(row[x]);
if (bits[FI_RGBA_ALPHA] != 0) {
has_alpha = TRUE;
}
bits += 4;
}
row += width;
}
} else {
// 24-bit RGB
for (uint32 y = 0; y < height; y++) {
BYTE *bits = FreeImage_GetScanLine(dib, y);
for (uint32 x = 0; x < width; x++) {
bits[FI_RGBA_BLUE] = (BYTE)TIFFGetB(row[x]);
bits[FI_RGBA_GREEN] = (BYTE)TIFFGetG(row[x]);
bits[FI_RGBA_RED] = (BYTE)TIFFGetR(row[x]);
bits += 3;
}
row += width;
}
}
_TIFFfree(raster);
}
// ### Not correct when header only
FreeImage_SetTransparent(dib, has_alpha);
} else if(loadMethod == LoadAs8BitTrns) {
// ---------------------------------------------------------------------------------
// 8-bit + 8-bit alpha layer loading
// ---------------------------------------------------------------------------------
// create a new 8-bit DIB
dib = CreateImageType(header_only, image_type, width, height, bitspersample, MIN<uint16>(2, samplesperpixel));
if (dib == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
// set up the colormap based on photometric
ReadPalette(tif, photometric, bitspersample, dib);
// calculate the line + pitch (separate for scr & dest)
const tmsize_t src_line = TIFFScanlineSize(tif);
// here, the pitch is 2x less than the original as we only keep the first layer
int dst_pitch = FreeImage_GetPitch(dib);
// transparency table for 8-bit + 8-bit alpha images
BYTE trns[256];
// clear the transparency table
memset(trns, 0xFF, 256 * sizeof(BYTE));
// In the tiff file the lines are saved from up to down
// In a DIB the lines must be saved from down to up
BYTE *bits = FreeImage_GetScanLine(dib, height - 1);
// read the tiff lines and save them in the DIB
if(planar_config == PLANARCONFIG_CONTIG && !header_only) {
BYTE *buf = (BYTE*)malloc(TIFFStripSize(tif) * sizeof(BYTE));
if(buf == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y += rowsperstrip) {
int32 nrow = (y + rowsperstrip > height ? height - y : rowsperstrip);
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), buf, nrow * src_line) == -1) {
free(buf);
throw FI_MSG_ERROR_PARSING;
}
for (int l = 0; l < nrow; l++) {
BYTE *p = bits;
BYTE *b = buf + l * src_line;
for(uint32 x = 0; x < (uint32)(src_line / samplesperpixel); x++) {
// copy the 8-bit layer
*p = b[0];
// convert the 8-bit alpha layer to a trns table
trns[ b[0] ] = b[1];
p++;
b += samplesperpixel;
}
bits -= dst_pitch;
}
}
free(buf);
}
else if(planar_config == PLANARCONFIG_SEPARATE && !header_only) {
tmsize_t stripsize = TIFFStripSize(tif) * sizeof(BYTE);
BYTE *buf = (BYTE*)malloc(2 * stripsize);
if(buf == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
BYTE *grey = buf;
BYTE *alpha = buf + stripsize;
for (uint32 y = 0; y < height; y += rowsperstrip) {
int32 nrow = (y + rowsperstrip > height ? height - y : rowsperstrip);
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), grey, nrow * src_line) == -1) {
free(buf);
throw FI_MSG_ERROR_PARSING;
}
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 1), alpha, nrow * src_line) == -1) {
free(buf);
throw FI_MSG_ERROR_PARSING;
}
for (int l = 0; l < nrow; l++) {
BYTE *p = bits;
BYTE *g = grey + l * src_line;
BYTE *a = alpha + l * src_line;
for(uint32 x = 0; x < (uint32)(src_line); x++) {
// copy the 8-bit layer
*p = g[0];
// convert the 8-bit alpha layer to a trns table
trns[ g[0] ] = a[0];
p++;
g++;
a++;
}
bits -= dst_pitch;
}
}
free(buf);
}
FreeImage_SetTransparencyTable(dib, &trns[0], 256);
FreeImage_SetTransparent(dib, TRUE);
} else if(loadMethod == LoadAsCMYK) {
// ---------------------------------------------------------------------------------
// CMYK loading
// ---------------------------------------------------------------------------------
// At this place, samplesperpixel could be > 4, esp. when a CMYK(A) format
// is recognized. Where all other formats are handled straight-forward, this
// format has to be handled special
BOOL isCMYKA = (photometric == PHOTOMETRIC_SEPARATED) && (samplesperpixel > 4);
// We use a temp dib to store the alpha for the CMYKA to RGBA conversion
// NOTE this is until we have Extra channels implementation.
// Also then it will be possible to merge LoadAsCMYK with LoadAsGenericStrip
FIBITMAP *alpha = NULL;
unsigned alpha_pitch = 0;
BYTE *alpha_bits = NULL;
unsigned alpha_Bpp = 0;
if(isCMYKA && !asCMYK && !header_only) {
if(bitspersample == 16) {
alpha = FreeImage_AllocateT(FIT_UINT16, width, height);
} else if (bitspersample == 8) {
alpha = FreeImage_Allocate(width, height, 8);
}
if (!alpha) {
FreeImage_OutputMessageProc(s_format_id, "Failed to allocate temporary alpha channel");
} else {
alpha_bits = FreeImage_GetScanLine(alpha, height - 1);
alpha_pitch = FreeImage_GetPitch(alpha);
alpha_Bpp = FreeImage_GetBPP(alpha) / 8;
}
}
// create a new DIB
const uint16 chCount = MIN<uint16>(samplesperpixel, 4);
dib = CreateImageType(header_only, image_type, width, height, bitspersample, chCount);
if (dib == NULL) {
FreeImage_Unload(alpha);
throw FI_MSG_ERROR_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
if (!header_only) {
// calculate the line + pitch (separate for scr & dest)
const tmsize_t src_line = TIFFScanlineSize(tif);
const tmsize_t dst_line = FreeImage_GetLine(dib);
const unsigned dib_pitch = FreeImage_GetPitch(dib);
const unsigned dibBpp = FreeImage_GetBPP(dib) / 8;
const unsigned Bpc = dibBpp / chCount;
const unsigned srcBpp = bitspersample * samplesperpixel / 8;
assert(Bpc <= 2); //< CMYK is only BYTE or SHORT
// In the tiff file the lines are save from up to down
// In a DIB the lines must be saved from down to up
BYTE *bits = FreeImage_GetScanLine(dib, height - 1);
// read the tiff lines and save them in the DIB
BYTE *buf = (BYTE*)malloc(TIFFStripSize(tif) * sizeof(BYTE));
if(buf == NULL) {
FreeImage_Unload(alpha);
throw FI_MSG_ERROR_MEMORY;
}
if(planar_config == PLANARCONFIG_CONTIG) {
// - loop for strip blocks -
for (uint32 y = 0; y < height; y += rowsperstrip) {
const int32 strips = (y + rowsperstrip > height ? height - y : rowsperstrip);
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), buf, strips * src_line) == -1) {
free(buf);
FreeImage_Unload(alpha);
throw FI_MSG_ERROR_PARSING;
}
// - loop for strips -
if(src_line != dst_line) {
// CMYKA+
if(alpha) {
for (int l = 0; l < strips; l++) {
for(BYTE *pixel = bits, *al_pixel = alpha_bits, *src_pixel = buf + l * src_line; pixel < bits + dib_pitch; pixel += dibBpp, al_pixel += alpha_Bpp, src_pixel += srcBpp) {
// copy pixel byte by byte
BYTE b = 0;
for ( ; b < dibBpp; ++b) {
pixel[b] = src_pixel[b];
}
// TODO write the remaining bytes to extra channel(s)
// HACK write the first alpha to a separate dib (assume BYTE or WORD)
al_pixel[0] = src_pixel[b];
if(Bpc > 1) {
al_pixel[1] = src_pixel[b + 1];
}
}
bits -= dib_pitch;
alpha_bits -= alpha_pitch;
}
}
else {
// alpha/extra channels alloc failed
for (int l = 0; l < strips; l++) {
for(BYTE* pixel = bits, * src_pixel = buf + l * src_line; pixel < bits + dst_line; pixel += dibBpp, src_pixel += srcBpp) {
AssignPixel(pixel, src_pixel, dibBpp);
}
bits -= dib_pitch;
}
}
}
else {
// CMYK to CMYK
for (int l = 0; l < strips; l++) {
BYTE *b = buf + l * src_line;
memcpy(bits, b, src_line);
bits -= dib_pitch;
}
}
} // height
}
else if(planar_config == PLANARCONFIG_SEPARATE) {
BYTE *dib_strip = bits;
BYTE *al_strip = alpha_bits;
// - loop for strip blocks -
for (uint32 y = 0; y < height; y += rowsperstrip) {
const int32 strips = (y + rowsperstrip > height ? height - y : rowsperstrip);
// - loop for channels (planes) -
for(uint16 sample = 0; sample < samplesperpixel; sample++) {
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, sample), buf, strips * src_line) == -1) {
free(buf);
FreeImage_Unload(alpha);
throw FI_MSG_ERROR_PARSING;
}
BYTE *dst_strip = dib_strip;
unsigned dst_pitch = dib_pitch;
uint16 ch = sample;
unsigned Bpp = dibBpp;
if(sample >= chCount) {
// TODO Write to Extra Channel
// HACK redirect write to temp alpha
if(alpha && sample == chCount) {
dst_strip = al_strip;
dst_pitch = alpha_pitch;
ch = 0;
Bpp = alpha_Bpp;
}
else {
break;
}
}
const unsigned channelOffset = ch * Bpc;
// - loop for strips in block -
BYTE *src_line_begin = buf;
BYTE *dst_line_begin = dst_strip;
for (int l = 0; l < strips; l++, src_line_begin += src_line, dst_line_begin -= dst_pitch ) {
// - loop for pixels in strip -
const BYTE* const src_line_end = src_line_begin + src_line;
for (BYTE *src_bits = src_line_begin, * dst_bits = dst_line_begin; src_bits < src_line_end; src_bits += Bpc, dst_bits += Bpp) {
AssignPixel(dst_bits + channelOffset, src_bits, Bpc);
} // line
} // strips
} // channels
// done with a strip block, incr to the next
dib_strip -= strips * dib_pitch;
al_strip -= strips * alpha_pitch;
} //< height
}
free(buf);
if (!asCMYK) {
ConvertCMYKtoRGBA(dib);
// The ICC Profile is invalid, clear it
iccSize = 0;
iccBuf = NULL;
if(isCMYKA) {
// HACK until we have Extra channels. (ConvertCMYKtoRGBA will then do the work)
FreeImage_SetChannel(dib, alpha, FICC_ALPHA);
FreeImage_Unload(alpha);
alpha = NULL;
}
else {
FIBITMAP *t = RemoveAlphaChannel(dib);
if(t) {
FreeImage_Unload(dib);
dib = t;
}
else {
FreeImage_OutputMessageProc(s_format_id, "Cannot allocate memory for buffer. CMYK image converted to RGB + pending Alpha");
}
}
}
} // !header_only
} else if(loadMethod == LoadAsGenericStrip) {
// ---------------------------------------------------------------------------------
// Generic loading
// ---------------------------------------------------------------------------------
// create a new DIB
const uint16 chCount = MIN<uint16>(samplesperpixel, 4);
dib = CreateImageType(header_only, image_type, width, height, bitspersample, chCount);
if (dib == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
// set up the colormap based on photometric
ReadPalette(tif, photometric, bitspersample, dib);
if (!header_only) {
// calculate the line + pitch (separate for scr & dest)
const tmsize_t src_line = TIFFScanlineSize(tif);
const tmsize_t dst_line = FreeImage_GetLine(dib);
const unsigned dst_pitch = FreeImage_GetPitch(dib);
const unsigned Bpp = FreeImage_GetBPP(dib) / 8;
const unsigned srcBpp = bitspersample * samplesperpixel / 8;
// In the tiff file the lines are save from up to down
// In a DIB the lines must be saved from down to up
BYTE *bits = FreeImage_GetScanLine(dib, height - 1);
// read the tiff lines and save them in the DIB
BYTE *buf = (BYTE*)malloc(TIFFStripSize(tif) * sizeof(BYTE));
if(buf == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
BOOL bThrowMessage = FALSE;
if(planar_config == PLANARCONFIG_CONTIG) {
for (uint32 y = 0; y < height; y += rowsperstrip) {
int32 strips = (y + rowsperstrip > height ? height - y : rowsperstrip);
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), buf, strips * src_line) == -1) {
// ignore errors as they can be frequent and not really valid errors, especially with fax images
bThrowMessage = TRUE;
/*
free(buf);
throw FI_MSG_ERROR_PARSING;
*/
}
if(src_line == dst_line) {
// channel count match
for (int l = 0; l < strips; l++) {
memcpy(bits, buf + l * src_line, src_line);
bits -= dst_pitch;
}
}
else {
for (int l = 0; l < strips; l++) {
for(BYTE *pixel = bits, *src_pixel = buf + l * src_line; pixel < bits + dst_pitch; pixel += Bpp, src_pixel += srcBpp) {
AssignPixel(pixel, src_pixel, Bpp);
}
bits -= dst_pitch;
}
}
}
}
else if(planar_config == PLANARCONFIG_SEPARATE) {
const unsigned Bpc = bitspersample / 8;
BYTE* dib_strip = bits;
// - loop for strip blocks -
for (uint32 y = 0; y < height; y += rowsperstrip) {
const int32 strips = (y + rowsperstrip > height ? height - y : rowsperstrip);
// - loop for channels (planes) -
for(uint16 sample = 0; sample < samplesperpixel; sample++) {
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, sample), buf, strips * src_line) == -1) {
// ignore errors as they can be frequent and not really valid errors, especially with fax images
bThrowMessage = TRUE;
}
if(sample >= chCount) {
// TODO Write to Extra Channel
break;
}
const unsigned channelOffset = sample * Bpc;
// - loop for strips in block -
BYTE* src_line_begin = buf;
BYTE* dst_line_begin = dib_strip;
for (int l = 0; l < strips; l++, src_line_begin += src_line, dst_line_begin -= dst_pitch ) {
// - loop for pixels in strip -
const BYTE* const src_line_end = src_line_begin + src_line;
for (BYTE* src_bits = src_line_begin, * dst_bits = dst_line_begin; src_bits < src_line_end; src_bits += Bpc, dst_bits += Bpp) {
// actually assigns channel
AssignPixel(dst_bits + channelOffset, src_bits, Bpc);
} // line
} // strips
} // channels
// done with a strip block, incr to the next
dib_strip -= strips * dst_pitch;
} // height
}
free(buf);
if(bThrowMessage) {
FreeImage_OutputMessageProc(s_format_id, "Warning: parsing error. Image may be incomplete or contain invalid data !");
}
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
SwapRedBlue32(dib);
#endif
} // !header only
} else if(loadMethod == LoadAsTiled) {
// ---------------------------------------------------------------------------------
// Tiled image loading
// ---------------------------------------------------------------------------------
uint32 tileWidth, tileHeight;
uint32 src_line = 0;
// create a new DIB
dib = CreateImageType( header_only, image_type, width, height, bitspersample, samplesperpixel);
if (dib == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
// set up the colormap based on photometric
ReadPalette(tif, photometric, bitspersample, dib);
// get the tile geometry
if (!TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tileWidth) || !TIFFGetField(tif, TIFFTAG_TILELENGTH, &tileHeight)) {
throw "Invalid tiled TIFF image";
}
// read the tiff lines and save them in the DIB
if(planar_config == PLANARCONFIG_CONTIG && !header_only) {
// get the maximum number of bytes required to contain a tile
tmsize_t tileSize = TIFFTileSize(tif);
// allocate tile buffer
BYTE *tileBuffer = (BYTE*)malloc(tileSize * sizeof(BYTE));
if(tileBuffer == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// calculate src line and dst pitch
int dst_pitch = FreeImage_GetPitch(dib);
int tileRowSize = TIFFTileRowSize(tif);
int imageRowSize = TIFFScanlineSize(tif);
// In the tiff file the lines are saved from up to down
// In a DIB the lines must be saved from down to up
BYTE *bits = FreeImage_GetScanLine(dib, height - 1);
uint32 x, y, rowSize;
for (y = 0; y < height; y += tileHeight) {
int32 nrows = (y + tileHeight > height ? height - y : tileHeight);
for (x = 0, rowSize = 0; x < width; x += tileWidth, rowSize += tileRowSize) {
memset(tileBuffer, 0, tileSize);
// read one tile
if (TIFFReadTile(tif, tileBuffer, x, y, 0, 0) < 0) {
free(tileBuffer);
throw "Corrupted tiled TIFF file";
}
// convert to strip
if(x + tileWidth > width) {
src_line = imageRowSize - rowSize;
} else {
src_line = tileRowSize;
}
BYTE *src_bits = tileBuffer;
BYTE *dst_bits = bits + rowSize;
for(int k = 0; k < nrows; k++) {
memcpy(dst_bits, src_bits, src_line);
src_bits += tileRowSize;
dst_bits -= dst_pitch;
}
}
bits -= nrows * dst_pitch;
}
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
SwapRedBlue32(dib);
#endif
free(tileBuffer);
}
else if(planar_config == PLANARCONFIG_SEPARATE) {
throw "Separated tiled TIFF images are not supported";
}
} else if(loadMethod == LoadAsLogLuv) {
// ---------------------------------------------------------------------------------
// RGBF LogLuv compressed loading
// ---------------------------------------------------------------------------------
double stonits; // input conversion to nits
if (!TIFFGetField(tif, TIFFTAG_STONITS, &stonits)) {
stonits = 1;
}
// create a new DIB
dib = CreateImageType(header_only, image_type, width, height, bitspersample, samplesperpixel);
if (dib == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
if(planar_config == PLANARCONFIG_CONTIG && !header_only) {
// calculate the line + pitch (separate for scr & dest)
tmsize_t src_line = TIFFScanlineSize(tif);
int dst_pitch = FreeImage_GetPitch(dib);
// In the tiff file the lines are save from up to down
// In a DIB the lines must be saved from down to up
BYTE *bits = FreeImage_GetScanLine(dib, height - 1);
// read the tiff lines and save them in the DIB
BYTE *buf = (BYTE*)malloc(TIFFStripSize(tif) * sizeof(BYTE));
if(buf == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y += rowsperstrip) {
int32 nrow = (y + rowsperstrip > height ? height - y : rowsperstrip);
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), buf, nrow * src_line) == -1) {
free(buf);
throw FI_MSG_ERROR_PARSING;
}
// convert from XYZ to RGB
for (int l = 0; l < nrow; l++) {
tiff_ConvertLineXYZToRGB(bits, buf + l * src_line, stonits, width);
bits -= dst_pitch;
}
}
free(buf);
}
else if(planar_config == PLANARCONFIG_SEPARATE) {
// this cannot happen according to the LogLuv specification
throw "Unable to handle PLANARCONFIG_SEPARATE LogLuv images";
}
} else if(loadMethod == LoadAsHalfFloat) {
// ---------------------------------------------------------------------------------
// RGBF loading from a half format
// ---------------------------------------------------------------------------------
// create a new DIB
dib = CreateImageType(header_only, image_type, width, height, bitspersample, samplesperpixel);
if (dib == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// fill in the resolution (english or universal)
ReadResolution(tif, dib);
if (!header_only) {
// calculate the line + pitch (separate for scr & dest)
tmsize_t src_line = TIFFScanlineSize(tif);
unsigned dst_pitch = FreeImage_GetPitch(dib);
// In the tiff file the lines are save from up to down
// In a DIB the lines must be saved from down to up
BYTE *bits = FreeImage_GetScanLine(dib, height - 1);
// read the tiff lines and save them in the DIB
if(planar_config == PLANARCONFIG_CONTIG) {
BYTE *buf = (BYTE*)malloc(TIFFStripSize(tif) * sizeof(BYTE));
if(buf == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y += rowsperstrip) {
uint32 nrow = (y + rowsperstrip > height ? height - y : rowsperstrip);
if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), buf, nrow * src_line) == -1) {
free(buf);
throw FI_MSG_ERROR_PARSING;
}
// convert from half (16-bit) to float (32-bit)
// !!! use OpenEXR half helper class
half half_value;
for (uint32 l = 0; l < nrow; l++) {
WORD *src_pixel = (WORD*)(buf + l * src_line);
float *dst_pixel = (float*)bits;
for(tmsize_t x = 0; x < (tmsize_t)(src_line / sizeof(WORD)); x++) {
half_value.setBits(src_pixel[x]);
dst_pixel[x] = half_value;
}
bits -= dst_pitch;
}
}
free(buf);
}
else if(planar_config == PLANARCONFIG_SEPARATE) {
// this use case was never encountered yet
throw "Unable to handle PLANARCONFIG_SEPARATE RGB half float images";
}
} // !header only
} else {
// ---------------------------------------------------------------------------------
// Unknown or unsupported format
// ---------------------------------------------------------------------------------
throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
}
// copy ICC profile data (must be done after FreeImage_Allocate)
FreeImage_CreateICCProfile(dib, iccBuf, iccSize);
if (photometric == PHOTOMETRIC_SEPARATED && asCMYK) {
FreeImage_GetICCProfile(dib)->flags |= FIICC_COLOR_IS_CMYK;
}
// copy TIFF metadata (must be done after FreeImage_Allocate)
ReadMetadata(tif, dib);
// copy TIFF thumbnail (must be done after FreeImage_Allocate)
ReadThumbnail(io, handle, data, tif, dib);
return (FIBITMAP *)dib;
} catch (const char *message) {
if(dib) {
FreeImage_Unload(dib);
}
if(message) {
FreeImage_OutputMessageProc(s_format_id, message);
}
return NULL;
}
}
// --------------------------------------------------------------------------
static BOOL
SaveOneTIFF(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data, unsigned ifd, unsigned ifdCount) {
if (!dib || !handle || !data) {
return FALSE;
}
try {
fi_TIFFIO *fio = (fi_TIFFIO*)data;
TIFF *out = fio->tif;
const FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(dib);
const uint32 width = FreeImage_GetWidth(dib);
const uint32 height = FreeImage_GetHeight(dib);
const uint16 bitsperpixel = (uint16)FreeImage_GetBPP(dib);
const FIICCPROFILE* iccProfile = FreeImage_GetICCProfile(dib);
// setup out-variables based on dib and flag options
uint16 bitspersample;
uint16 samplesperpixel;
uint16 photometric;
if(image_type == FIT_BITMAP) {
// standard image: 1-, 4-, 8-, 16-, 24-, 32-bit
samplesperpixel = ((bitsperpixel == 24) ? 3 : ((bitsperpixel == 32) ? 4 : 1));
bitspersample = bitsperpixel / samplesperpixel;
photometric = GetPhotometric(dib);
if ((bitsperpixel == 8) && FreeImage_IsTransparent(dib)) {
// 8-bit transparent picture : convert later to 8-bit + 8-bit alpha
samplesperpixel = 2;
bitspersample = 8;
}
else if(bitsperpixel == 32) {
// 32-bit images : check for CMYK or alpha transparency
if ((((iccProfile->flags & FIICC_COLOR_IS_CMYK) == FIICC_COLOR_IS_CMYK) || ((flags & TIFF_CMYK) == TIFF_CMYK))) {
// CMYK support
photometric = PHOTOMETRIC_SEPARATED;
TIFFSetField(out, TIFFTAG_INKSET, INKSET_CMYK);
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, 4);
}
else if(photometric == PHOTOMETRIC_RGB) {
// transparency mask support
uint16 sampleinfo[1];
// unassociated alpha data is transparency information
sampleinfo[0] = EXTRASAMPLE_UNASSALPHA;
TIFFSetField(out, TIFFTAG_EXTRASAMPLES, 1, sampleinfo);
}
}
} else if(image_type == FIT_RGB16) {
// 48-bit RGB
samplesperpixel = 3;
bitspersample = bitsperpixel / samplesperpixel;
photometric = PHOTOMETRIC_RGB;
} else if(image_type == FIT_RGBA16) {
// 64-bit RGBA
samplesperpixel = 4;
bitspersample = bitsperpixel / samplesperpixel;
if ((((iccProfile->flags & FIICC_COLOR_IS_CMYK) == FIICC_COLOR_IS_CMYK) || ((flags & TIFF_CMYK) == TIFF_CMYK))) {
// CMYK support
photometric = PHOTOMETRIC_SEPARATED;
TIFFSetField(out, TIFFTAG_INKSET, INKSET_CMYK);
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, 4);
}
else {
photometric = PHOTOMETRIC_RGB;
// transparency mask support
uint16 sampleinfo[1];
// unassociated alpha data is transparency information
sampleinfo[0] = EXTRASAMPLE_UNASSALPHA;
TIFFSetField(out, TIFFTAG_EXTRASAMPLES, 1, sampleinfo);
}
} else if(image_type == FIT_RGBF) {
// 96-bit RGBF => store with a LogLuv encoding ?
samplesperpixel = 3;
bitspersample = bitsperpixel / samplesperpixel;
// the library converts to and from floating-point XYZ CIE values
if ((flags & TIFF_LOGLUV) == TIFF_LOGLUV) {
photometric = PHOTOMETRIC_LOGLUV;
TIFFSetField(out, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_FLOAT);
// TIFFSetField(out, TIFFTAG_STONITS, 1.0); // assume unknown
}
else {
// store with default compression (LZW) or with input compression flag
photometric = PHOTOMETRIC_RGB;
}
} else if (image_type == FIT_RGBAF) {
// 128-bit RGBAF => store with default compression (LZW) or with input compression flag
samplesperpixel = 4;
bitspersample = bitsperpixel / samplesperpixel;
photometric = PHOTOMETRIC_RGB;
} else {
// special image type (int, long, double, ...)
samplesperpixel = 1;
bitspersample = bitsperpixel;
photometric = PHOTOMETRIC_MINISBLACK;
}
// set image data type
WriteImageType(out, image_type);
// write possible ICC profile
if (iccProfile->size && iccProfile->data) {
TIFFSetField(out, TIFFTAG_ICCPROFILE, iccProfile->size, iccProfile->data);
}
// handle standard width/height/bpp stuff
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bitspersample);
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); // single image plane
TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
TIFFSetField(out, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(out, (uint32) -1));
// handle metrics
WriteResolution(out, dib);
// multi-paging
if (page >= 0) {
char page_number[20];
sprintf(page_number, "Page %d", page);
TIFFSetField(out, TIFFTAG_SUBFILETYPE, (uint32)FILETYPE_PAGE);
TIFFSetField(out, TIFFTAG_PAGENUMBER, (uint16)page, (uint16)0);
TIFFSetField(out, TIFFTAG_PAGENAME, page_number);
} else {
// is it a thumbnail ?
TIFFSetField(out, TIFFTAG_SUBFILETYPE, (ifd == 0) ? (uint32)0 : (uint32)FILETYPE_REDUCEDIMAGE);
}
// palettes (image colormaps are automatically scaled to 16-bits)
if (photometric == PHOTOMETRIC_PALETTE) {
uint16 *r, *g, *b;
uint16 nColors = (uint16)FreeImage_GetColorsUsed(dib);
RGBQUAD *pal = FreeImage_GetPalette(dib);
r = (uint16 *) _TIFFmalloc(sizeof(uint16) * 3 * nColors);
if(r == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
g = r + nColors;
b = g + nColors;
for (int i = nColors - 1; i >= 0; i--) {
r[i] = SCALE((uint16)pal[i].rgbRed);
g[i] = SCALE((uint16)pal[i].rgbGreen);
b[i] = SCALE((uint16)pal[i].rgbBlue);
}
TIFFSetField(out, TIFFTAG_COLORMAP, r, g, b);
_TIFFfree(r);
}
// compression tag
WriteCompression(out, bitspersample, samplesperpixel, photometric, flags);
// metadata
WriteMetadata(out, dib);
// thumbnail tag
if ((ifd == 0) && (ifdCount > 1)) {
uint16 nsubifd = 1;
uint64 subifd[1];
subifd[0] = 0;
TIFFSetField(out, TIFFTAG_SUBIFD, nsubifd, subifd);
}
// read the DIB lines from bottom to top
// and save them in the TIF
// -------------------------------------
const uint32 pitch = FreeImage_GetPitch(dib);
if(image_type == FIT_BITMAP) {
// standard bitmap type
switch(bitsperpixel) {
case 1 :
case 4 :
case 8 :
{
if ((bitsperpixel == 8) && FreeImage_IsTransparent(dib)) {
// 8-bit transparent picture : convert to 8-bit + 8-bit alpha
// get the transparency table
BYTE *trns = FreeImage_GetTransparencyTable(dib);
BYTE *buffer = (BYTE *)malloc(2 * width * sizeof(BYTE));
if(buffer == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (int y = height - 1; y >= 0; y--) {
BYTE *bits = FreeImage_GetScanLine(dib, y);
BYTE *p = bits, *b = buffer;
for(uint32 x = 0; x < width; x++) {
// copy the 8-bit layer
b[0] = *p;
// convert the trns table to a 8-bit alpha layer
b[1] = trns[ b[0] ];
p++;
b += samplesperpixel;
}
// write the scanline to disc
TIFFWriteScanline(out, buffer, height - y - 1, 0);
}
free(buffer);
}
else {
// other cases
BYTE *buffer = (BYTE *)malloc(pitch * sizeof(BYTE));
if(buffer == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y++) {
// get a copy of the scanline
memcpy(buffer, FreeImage_GetScanLine(dib, height - y - 1), pitch);
// write the scanline to disc
TIFFWriteScanline(out, buffer, y, 0);
}
free(buffer);
}
break;
}
case 24:
case 32:
{
BYTE *buffer = (BYTE *)malloc(pitch * sizeof(BYTE));
if(buffer == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y++) {
// get a copy of the scanline
memcpy(buffer, FreeImage_GetScanLine(dib, height - y - 1), pitch);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
if (photometric != PHOTOMETRIC_SEPARATED) {
// TIFFs store color data RGB(A) instead of BGR(A)
BYTE *pBuf = buffer;
for (uint32 x = 0; x < width; x++) {
INPLACESWAP(pBuf[0], pBuf[2]);
pBuf += samplesperpixel;
}
}
#endif
// write the scanline to disc
TIFFWriteScanline(out, buffer, y, 0);
}
free(buffer);
break;
}
}//< switch (bitsperpixel)
} else if(image_type == FIT_RGBF && (flags & TIFF_LOGLUV) == TIFF_LOGLUV) {
// RGBF image => store as XYZ using a LogLuv encoding
BYTE *buffer = (BYTE *)malloc(pitch * sizeof(BYTE));
if(buffer == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y++) {
// get a copy of the scanline and convert from RGB to XYZ
tiff_ConvertLineRGBToXYZ(buffer, FreeImage_GetScanLine(dib, height - y - 1), width);
// write the scanline to disc
TIFFWriteScanline(out, buffer, y, 0);
}
free(buffer);
} else {
// just dump the dib (tiff supports all dib types)
BYTE *buffer = (BYTE *)malloc(pitch * sizeof(BYTE));
if(buffer == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
for (uint32 y = 0; y < height; y++) {
// get a copy of the scanline
memcpy(buffer, FreeImage_GetScanLine(dib, height - y - 1), pitch);
// write the scanline to disc
TIFFWriteScanline(out, buffer, y, 0);
}
free(buffer);
}
// write out the directory tag if we wrote a page other than -1 or if we have a thumbnail to write later
if ( (page >= 0) || ((ifd == 0) && (ifdCount > 1)) ) {
TIFFWriteDirectory(out);
// else: TIFFClose will WriteDirectory
}
return TRUE;
} catch(const char *text) {
FreeImage_OutputMessageProc(s_format_id, text);
return FALSE;
}
}
static BOOL DLL_CALLCONV
Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
BOOL bResult = FALSE;
// handle thumbnail as SubIFD
const BOOL bHasThumbnail = (FreeImage_GetThumbnail(dib) != NULL);
const unsigned ifdCount = bHasThumbnail ? 2 : 1;
FIBITMAP *bitmap = dib;
for(unsigned ifd = 0; ifd < ifdCount; ifd++) {
// redirect dib to thumbnail for the second pass
if(ifd == 1) {
bitmap = FreeImage_GetThumbnail(dib);
}
bResult = SaveOneTIFF(io, bitmap, handle, page, flags, data, ifd, ifdCount);
if (!bResult) {
return FALSE;
}
}
return bResult;
}
// ==========================================================
// Init
// ==========================================================
void DLL_CALLCONV
InitTIFF(Plugin *plugin, int format_id) {
s_format_id = format_id;
plugin->format_proc = Format;
plugin->description_proc = Description;
plugin->extension_proc = Extension;
plugin->regexpr_proc = RegExpr;
plugin->open_proc = Open;
plugin->close_proc = Close;
plugin->pagecount_proc = PageCount;
plugin->pagecapability_proc = NULL;
plugin->load_proc = Load;
plugin->save_proc = Save;
plugin->validate_proc = Validate;
plugin->mime_proc = MimeType;
plugin->supports_export_bpp_proc = SupportsExportDepth;
plugin->supports_export_type_proc = SupportsExportType;
plugin->supports_icc_profiles_proc = SupportsICCProfiles;
plugin->supports_no_pixels_proc = SupportsNoPixels;
}
|