-
-
Notifications
You must be signed in to change notification settings - Fork 310
/
TIFFImageReader.java
2948 lines (2455 loc) · 144 KB
/
TIFFImageReader.java
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
/*
* Copyright (c) 2012, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.plugins.tiff;
import com.twelvemonkeys.imageio.ImageReaderBase;
import com.twelvemonkeys.imageio.color.CIELabColorConverter;
import com.twelvemonkeys.imageio.color.CIELabColorConverter.Illuminant;
import com.twelvemonkeys.imageio.color.ColorProfiles;
import com.twelvemonkeys.imageio.color.ColorSpaces;
import com.twelvemonkeys.imageio.color.YCbCrConverter;
import com.twelvemonkeys.imageio.metadata.CompoundDirectory;
import com.twelvemonkeys.imageio.metadata.Directory;
import com.twelvemonkeys.imageio.metadata.Entry;
import com.twelvemonkeys.imageio.metadata.iptc.IPTCReader;
import com.twelvemonkeys.imageio.metadata.jpeg.JPEG;
import com.twelvemonkeys.imageio.metadata.psd.PSD;
import com.twelvemonkeys.imageio.metadata.psd.PSDReader;
import com.twelvemonkeys.imageio.metadata.tiff.Half;
import com.twelvemonkeys.imageio.metadata.tiff.Rational;
import com.twelvemonkeys.imageio.metadata.tiff.TIFF;
import com.twelvemonkeys.imageio.metadata.tiff.TIFFReader;
import com.twelvemonkeys.imageio.metadata.xmp.XMPReader;
import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream;
import com.twelvemonkeys.imageio.stream.DirectImageInputStream;
import com.twelvemonkeys.imageio.stream.SubImageInputStream;
import com.twelvemonkeys.imageio.util.IIOUtil;
import com.twelvemonkeys.imageio.util.ImageTypeSpecifiers;
import com.twelvemonkeys.imageio.util.ProgressListenerBase;
import com.twelvemonkeys.io.FastByteArrayOutputStream;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.io.enc.DecoderStream;
import com.twelvemonkeys.io.enc.PackBitsDecoder;
import com.twelvemonkeys.lang.StringUtil;
import org.w3c.dom.NodeList;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.event.IIOReadWarningListener;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.plugins.jpeg.JPEGImageReadParam;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.color.*;
import java.awt.image.*;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.zip.InflaterInputStream;
import static com.twelvemonkeys.imageio.util.IIOUtil.createStreamAdapter;
import static com.twelvemonkeys.imageio.util.IIOUtil.subsampleRow;
import static java.util.Arrays.asList;
/**
* ImageReader implementation for Aldus/Adobe Tagged Image File Format (TIFF).
* <p>
* The reader is supposed to be fully "Baseline TIFF" compliant, and supports the following image types:
* </p>
* <ul>
* <li>Class B (Bi-level), all relevant compression types, 1 bit per sample</li>
* <li>Class G (Gray), all relevant compression types, 2, 4, 8, 16 or 32 bits per sample, unsigned integer</li>
* <li>Class P (Palette/indexed color), all relevant compression types, 1, 2, 4, 8 or 16 bits per sample, unsigned integer</li>
* <li>Class R (RGB), all relevant compression types, 8 or 16 bits per sample, unsigned integer</li>
* </ul>
* In addition, it supports many common TIFF extensions such as:
* <ul>
* <li>Tiling</li>
* <li>Class F (Facsimile), CCITT T.4 and T.6 compression (types 3 and 4), 1 bit per sample</li>
* <li>LZW Compression (type 5)</li>
* <li>"Old-style" JPEG Compression (type 6), as a best effort, as the spec is not well-defined</li>
* <li>JPEG Compression (type 7)</li>
* <li>ZLib (aka Adobe-style Deflate) Compression (type 8)</li>
* <li>Deflate Compression (type 32946)</li>
* <li>Horizontal differencing Predictor (type 2) for LZW, ZLib, Deflate and PackBits compression</li>
* <li>Alpha channel (ExtraSamples types 1/Associated Alpha and 2/Unassociated Alpha)</li>
* <li>Class S, CMYK data (PhotometricInterpretation type 5/Separated)</li>
* <li>Class Y, YCbCr data (PhotometricInterpretation type 6/YCbCr for both JPEG and other compressions</li>
* <li>Planar data (PlanarConfiguration type 2/Planar)</li>
* <li>ICC profiles (ICCProfile)</li>
* <li>BitsPerSample values up to 16 for most PhotometricInterpretations</li>
* <li>Multiple images (pages) in one file</li>
* </ul>
*
* @see <a href="http://partners.adobe.com/public/developer/tiff/index.html">Adobe TIFF developer resources</a>
* @see <a href="http://www.alternatiff.com/resources/TIFF6.pdf">TIFF 6.0 specification</a>
* @see <a href="http://en.wikipedia.org/wiki/Tagged_Image_File_Format">Wikipedia TIFF</a>
* @see <a href="http://www.awaresystems.be/imaging/tiff.html">AWare Systems TIFF pages</a>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: TIFFImageReader.java,v 1.0 08.05.12 15:14 haraldk Exp$
*/
public final class TIFFImageReader extends ImageReaderBase {
// TODOs ImageIO basic functionality:
// TODO: Thumbnail support (what is a TIFF thumbnail anyway? Photoshop way? Or use subfiletype?)
// TODOs ImageIO advanced functionality:
// TODO: Implement readAsRenderedImage to allow tiled RenderedImage?
// For some layouts, we could do reads super-fast with a memory mapped buffer.
// TODO: Implement readRaster directly (100% correctly)
// TODOs Extension support
// TODO: Auto-rotate based on Orientation
// TODO: Support Compression 34712 (JPEG2000)? Depends on JPEG2000 ImageReader
// TODO: Support Compression 34661 (JBIG)? Depends on JBIG ImageReader
// DONE:
// Handle SampleFormat
// Support Compression 6 ('Old-style' JPEG)
// Support Compression 2 (CCITT Modified Huffman RLE) for bi-level images
// Source region
// Subsampling
// IIOMetadata (stay close to Sun's TIFF metadata)
// http://download.java.net/media/jai-imageio/javadoc/1.1/com/sun/media/imageio/plugins/tiff/package-summary.html#ImageMetadata
// Support ICCProfile
// Support PlanarConfiguration 2
// Support Compression 3 & 4 (CCITT T.4 & T.6)
// Support ExtraSamples (an array, if multiple extra samples!)
// (0: Unspecified (not alpha), 1: Associated Alpha (pre-multiplied), 2: Unassociated Alpha (non-multiplied)
final static boolean DEBUG = "true".equalsIgnoreCase(System.getProperty("com.twelvemonkeys.imageio.plugins.tiff.debug"));
// NOTE: DO NOT MODIFY OR EXPOSE THIS ARRAY OUTSIDE PACKAGE!
static final double[] CCIR_601_1_COEFFICIENTS = new double[] {299.0 / 1000.0, 587.0 / 1000.0, 114.0 / 1000.0};
static final double[] REFERENCE_BLACK_WHITE_YCC_DEFAULT = new double[] {0, 255, 128, 255, 128, 255};
private CompoundDirectory IFDs;
private Directory currentIFD;
private int overrideCCITTCompression = -1;
TIFFImageReader(final ImageReaderSpi provider) {
super(provider);
}
@Override
protected void resetMembers() {
IFDs = null;
currentIFD = null;
overrideCCITTCompression = -1;
}
private void readMetadata() throws IOException {
if (imageInput == null) {
throw new IllegalStateException("input not set");
}
if (IFDs == null) {
IFDs = (CompoundDirectory) new TIFFReader().read(imageInput); // NOTE: Sets byte order as a side effect
if (DEBUG) {
System.err.println("Byte order: " + imageInput.getByteOrder());
System.err.println("Number of images: " + IFDs.directoryCount());
for (int i = 0; i < IFDs.directoryCount(); i++) {
System.err.printf("IFD %d: %s\n", i, IFDs.getDirectory(i));
}
Entry tiffXMP = IFDs.getEntryById(TIFF.TAG_XMP);
if (tiffXMP != null) {
byte[] value = (byte[]) tiffXMP.getValue();
// The XMPReader doesn't like null-termination...
int len = value.length;
for (int i = len - 1; i > 0; i--) {
if (value[i] == 0) {
len--;
}
else {
break;
}
}
Directory xmp = new XMPReader().read(new ByteArrayImageInputStream(value, 0, len));
System.err.println("-----------------------------------------------------------------------------");
System.err.println("xmp: " + xmp);
}
Entry tiffIPTC = IFDs.getEntryById(TIFF.TAG_IPTC);
if (tiffIPTC != null) {
Object value = tiffIPTC.getValue();
if (value instanceof short[]) {
System.err.println("short[]: " + value);
}
if (value instanceof long[]) {
// As seen in a Magick produced image...
System.err.println("long[]: " + value);
long[] longs = (long[]) value;
value = new byte[longs.length * 8];
ByteBuffer.wrap((byte[]) value).asLongBuffer().put(longs);
}
if (value instanceof float[]) {
System.err.println("float[]: " + value);
}
if (value instanceof double[]) {
System.err.println("double[]: " + value);
}
Directory iptc = new IPTCReader().read(new ByteArrayImageInputStream((byte[]) value));
System.err.println("-----------------------------------------------------------------------------");
System.err.println("iptc: " + iptc);
}
Entry tiffPSD = IFDs.getEntryById(TIFF.TAG_PHOTOSHOP);
if (tiffPSD != null) {
Directory psd = new PSDReader().read(new ByteArrayImageInputStream((byte[]) tiffPSD.getValue()));
System.err.println("-----------------------------------------------------------------------------");
System.err.println("psd: " + psd);
}
Entry tiffPSD2 = IFDs.getEntryById(TIFF.TAG_PHOTOSHOP_IMAGE_SOURCE_DATA);
if (tiffPSD2 != null) {
byte[] value = (byte[]) tiffPSD2.getValue();
String foo = "Adobe Photoshop Document Data Block";
if (Arrays.equals(foo.getBytes(StandardCharsets.US_ASCII), Arrays.copyOf(value, foo.length()))) {
System.err.println("foo: " + foo);
int offset = foo.length() + 1;
ImageInputStream input = new ByteArrayImageInputStream(value, offset, value.length - offset);
// input.setByteOrder(ByteOrder.LITTLE_ENDIAN); // TODO: WHY???!
while (input.getStreamPosition() < value.length - offset) {
int resourceId = input.readInt();
if (resourceId != PSD.RESOURCE_TYPE) {
System.err.println("Not a PSD resource: " + resourceId);
break;
}
int resourceKey = input.readInt();
System.err.println("resourceKey: " + intToStr(resourceKey));
long resourceLength = input.readUnsignedInt();
System.err.println("resourceLength: " + resourceLength);
long pad = (4 - (resourceLength % 4)) % 4;
long resourceLengthPadded = resourceLength + pad; // Padded to 32 bit boundary, possibly 64 bit for 8B64 resources
long streamPosition = input.getStreamPosition();
if (resourceKey == ('L' << 24 | 'a' << 16 | 'y' << 8 | 'r')) {
short count = input.readShort();
System.err.println("layer count: " + count);
for (int layer = 0; layer < count; layer++) {
int top = input.readInt();
int left = input.readInt();
int bottom = input.readInt();
int right = input.readInt();
System.err.printf("%d, %d, %d, %d\n", top, left, bottom, right);
short channels = input.readShort();
System.err.println("channels: " + channels);
for (int channel = 0; channel < channels; channel++) {
short channelId = input.readShort();
System.err.println("channelId: " + channelId);
long channelLength = input.readUnsignedInt();
System.err.println("channelLength: " + channelLength);
}
System.err.println("8BIM: " + intToStr(input.readInt()));
int blendMode = input.readInt();
System.err.println("blend mode key: " + intToStr(blendMode));
int opacity = input.readUnsignedByte();
System.err.println("opacity: " + opacity);
int clipping = input.readUnsignedByte();
System.err.println("clipping: " + clipping);
byte flags = input.readByte();
System.err.printf("flags: 0x%02x\n", flags);
input.readByte(); // Pad
long layerExtraDataLength = input.readUnsignedInt();
long pos = input.getStreamPosition();
System.err.println("length: " + layerExtraDataLength);
long layerMaskSize = input.readUnsignedInt();
input.skipBytes(layerMaskSize);
long layerBlendingRangesSize = input.readUnsignedInt();
input.skipBytes(layerBlendingRangesSize);
String layerName = readPascalString(input);
System.err.println("layerName: " + layerName);
int mod = (layerName.length() + 1) % 4; // len + 1 for null-term
System.err.println("mod: " + mod);
if (mod != 0) {
input.skipBytes(4 - mod);
}
System.err.println("input.getStreamPosition(): " + input.getStreamPosition());
// TODO: More data here
System.err.println(TIFFReader.HexDump.dump(0, value, (int) (offset + input.getStreamPosition()), 64));
input.seek(pos + layerExtraDataLength);
}
// long len = input.readUnsignedInt();
// System.err.println("len: " + len);
//
// int count = input.readUnsignedShort();
// System.err.println("count: " + count);
System.err.println(TIFFReader.HexDump.dump(0, value, (int) (offset + input.getStreamPosition()), 64));
}
input.seek(streamPosition + resourceLengthPadded);
System.out.println("input.getStreamPosition(): " + input.getStreamPosition());
}
// Directory psd2 = new PSDReader().read(input);
// System.err.println("-----------------------------------------------------------------------------");
// System.err.println("psd2: " + psd2);
}
}
}
}
}
static String readPascalString(final DataInput pInput) throws IOException {
int length = pInput.readUnsignedByte();
if (length == 0) {
return "";
}
byte[] bytes = new byte[length];
pInput.readFully(bytes);
return StringUtil.decode(bytes, 0, bytes.length, "ASCII");
}
static String intToStr(int value) {
return new String(
new byte[]{
(byte) ((value & 0xff000000) >>> 24),
(byte) ((value & 0x00ff0000) >> 16),
(byte) ((value & 0x0000ff00) >> 8),
(byte) ((value & 0x000000ff))
}
);
}
private void readIFD(final int imageIndex) throws IOException {
readMetadata();
checkBounds(imageIndex);
currentIFD = IFDs.getDirectory(imageIndex);
overrideCCITTCompression = -1; // Reset override for next image
}
@Override
public int getNumImages(final boolean allowSearch) throws IOException {
readMetadata();
return IFDs.directoryCount();
}
private Number getValueAsNumberWithDefault(final int tag, final String tagName, final Number defaultValue) throws IIOException {
Entry entry = currentIFD.getEntryById(tag);
if (entry == null) {
if (defaultValue != null) {
return defaultValue;
}
throw new IIOException("Missing TIFF tag: " + (tagName != null ? tagName : tag));
}
return (Number) entry.getValue();
}
private long getValueAsLongWithDefault(final int tag, final String tagName, final Long defaultValue) throws IIOException {
return getValueAsNumberWithDefault(tag, tagName, defaultValue).longValue();
}
private long getValueAsLongWithDefault(final int tag, final Long defaultValue) throws IIOException {
return getValueAsLongWithDefault(tag, null, defaultValue);
}
private int getValueAsIntWithDefault(final int tag, final String tagName, final Integer defaultValue) throws IIOException {
return getValueAsNumberWithDefault(tag, tagName, defaultValue).intValue();
}
private int getValueAsIntWithDefault(final int tag, Integer defaultValue) throws IIOException {
return getValueAsIntWithDefault(tag, null, defaultValue);
}
private int getValueAsInt(final int tag, String tagName) throws IIOException {
return getValueAsIntWithDefault(tag, tagName, null);
}
@Override
public int getWidth(int imageIndex) throws IOException {
readIFD(imageIndex);
return getValueAsInt(TIFF.TAG_IMAGE_WIDTH, "ImageWidth");
}
@Override
public int getHeight(int imageIndex) throws IOException {
readIFD(imageIndex);
return getValueAsInt(TIFF.TAG_IMAGE_HEIGHT, "ImageHeight");
}
@Override
public ImageTypeSpecifier getRawImageType(int imageIndex) throws IOException {
readIFD(imageIndex);
int sampleFormat = getSampleFormat();
int planarConfiguration = getValueAsIntWithDefault(TIFF.TAG_PLANAR_CONFIGURATION, TIFFBaseline.PLANARCONFIG_CHUNKY);
int interpretation = getPhotometricInterpretationWithFallback();
int samplesPerPixel = getValueAsIntWithDefault(TIFF.TAG_SAMPLES_PER_PIXEL, 1);
int bitsPerSample = getBitsPerSample();
int dataType = getDataType(sampleFormat, bitsPerSample);
int opaqueSamplesPerPixel = getOpaqueSamplesPerPixel(interpretation);
// Spec says ExtraSamples are mandatory for extra samples, however known encoders
// (ie. SeaShore) writes ARGB TIFFs without ExtraSamples.
long[] extraSamples = getValueAsLongArray(TIFF.TAG_EXTRA_SAMPLES, "ExtraSamples", false);
if (extraSamples == null && samplesPerPixel > opaqueSamplesPerPixel) {
// TODO: Log warning!
// First extra is alpha, rest is "unspecified" (0)
extraSamples = new long[samplesPerPixel - opaqueSamplesPerPixel];
extraSamples[0] = TIFFBaseline.EXTRASAMPLE_UNASSOCIATED_ALPHA;
}
// Determine alpha
boolean hasAlpha = extraSamples != null
&& (extraSamples[0] == TIFFBaseline.EXTRASAMPLE_ASSOCIATED_ALPHA
|| extraSamples[0] == TIFFBaseline.EXTRASAMPLE_UNASSOCIATED_ALPHA);
boolean isAlphaPremultiplied = hasAlpha && extraSamples[0] == TIFFBaseline.EXTRASAMPLE_ASSOCIATED_ALPHA;
int significantSamples = opaqueSamplesPerPixel + (hasAlpha ? 1 : 0);
// Read embedded cs
ICC_Profile profile = getICCProfile();
ColorSpace cs;
switch (interpretation) {
// TIFF 6.0 baseline
case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
// WhiteIsZero
// We need special case to preserve WhiteIsZero for CCITT 1 bit encodings
// as some software will treat black/white runs as-is, regardless of photometric.
// Special handling is also in the normalizeColor method
if (significantSamples == 1 && bitsPerSample == 1) {
if (profile != null) {
processWarningOccurred("Ignoring embedded ICC color profile for Bi-level/Gray TIFF");
}
byte[] lut = new byte[] {-1, 0};
return ImageTypeSpecifier.createIndexed(lut, lut, lut, null, bitsPerSample, dataType);
}
// Otherwise, we'll handle this by inverting the values when reading
case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO:
// BlackIsZero
// Gray scale or B/W
switch (significantSamples) {
case 1:
// TIFF 6.0 Spec says: 1, 4 or 8 for baseline (1 for bi-level, 4/8 for gray)
// ImageTypeSpecifier supports 1, 2, 4, 8 or 16 bits per sample, we'll support 32 bits as well.
// (Chunky or planar makes no difference for a single channel).
if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_GRAY) {
processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (GRAY/type 6). Ignoring profile.", profile.getColorSpaceType()));
profile = null;
}
cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_GRAY) : ColorSpaces.createColorSpace(profile);
if (cs == ColorSpace.getInstance(ColorSpace.CS_GRAY) && (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 || bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32)) {
return ImageTypeSpecifiers.createGrayscale(bitsPerSample, dataType);
}
else if (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4) {
// Use packed format for 1/2/4 bits
return ImageTypeSpecifiers.createPackedGrayscale(cs, bitsPerSample, dataType);
}
else if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
return createImageTypeSpecifier(TIFFBaseline.PLANARCONFIG_CHUNKY, cs, dataType, significantSamples, samplesPerPixel, false, false);
}
else if (bitsPerSample % 2 == 0) {
ColorModel colorModel = new ComponentColorModel(cs, new int[] {bitsPerSample}, false, false, Transparency.OPAQUE, dataType);
return new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(1, 1));
}
throw new IIOException(String.format("Unsupported BitsPerSample for Bi-level/Gray TIFF (expected 1, 2, 4, 8, 16 or 32): %d", bitsPerSample));
case 2:
// Gray + alpha. We'll support:
// * 8, 16 or 32 bits per sample
// * Associated (pre-multiplied) or unassociated (non-pre-multiplied) alpha
// * Chunky (interleaved) or planar (banded) data
if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_GRAY) {
processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (GRAY/type 6). Ignoring profile.", profile.getColorSpaceType()));
profile = null;
}
cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_GRAY) : ColorSpaces.createColorSpace(profile);
if (cs == ColorSpace.getInstance(ColorSpace.CS_GRAY) && (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32)) {
switch (planarConfiguration) {
case TIFFBaseline.PLANARCONFIG_CHUNKY:
return ImageTypeSpecifiers.createGrayscale(bitsPerSample, dataType, isAlphaPremultiplied);
case TIFFExtension.PLANARCONFIG_PLANAR:
return ImageTypeSpecifiers.createBanded(cs, new int[] {0, 1}, new int[] {0, 0}, dataType, true, isAlphaPremultiplied);
}
}
else if (/*bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4 ||*/ bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
// TODO: Should use packed format for 1/2/4 chunky.
// TODO: For 1/2/4 bit planar, we might need to fix while reading... Look at IFFImageReader?
return createImageTypeSpecifier(planarConfiguration, cs, dataType, significantSamples, samplesPerPixel, true, isAlphaPremultiplied);
}
throw new IIOException(String.format("Unsupported BitsPerSample for Gray + Alpha TIFF (expected 8, 16 or 32): %d", bitsPerSample));
default:
throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for Bi-level/Gray TIFF (expected 1/1, 1/2, 1/4, 1/8, 1/16 or 1/32, or 2/8, 2/16 or 2/32): %d/%d", samplesPerPixel, bitsPerSample));
}
case TIFFExtension.PHOTOMETRIC_YCBCR:
// JPEG reader will handle YCbCr to RGB for us, otherwise we'll convert while reading
// TODO: Sanity check that we have SamplesPerPixel == 3, BitsPerSample == [8,8,8] (or [16,16,16]) and Compression == 1 (none), 5 (LZW), or 6 (JPEG)
case TIFFBaseline.PHOTOMETRIC_RGB:
// RGB
if (profile != null && profile.getColorSpaceType() != ColorSpace.TYPE_RGB) {
processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (RGB/type 5). Ignoring profile.", profile.getColorSpaceType()));
profile = null;
}
cs = profile == null ? ColorSpace.getInstance(ColorSpace.CS_sRGB) : ColorSpaces.createColorSpace(profile);
switch (significantSamples) {
case 3:
if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
return createImageTypeSpecifier(planarConfiguration, cs, dataType, significantSamples, samplesPerPixel, false, false);
}
else if (bitsPerSample == 2 && planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY) {
return ImageTypeSpecifiers.createPacked(cs, 0x30, 0xC, 0x3, 0, DataBuffer.TYPE_BYTE, false);
}
else if (bitsPerSample == 4 && planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY) {
return ImageTypeSpecifiers.createPacked(cs, 0xF00, 0xF0, 0xF, 0, DataBuffer.TYPE_USHORT, false);
}
else if (bitsPerSample > 8 && bitsPerSample % 2 == 0) {
ColorModel colorModel = new ComponentColorModel(cs, new int[] {bitsPerSample, bitsPerSample, bitsPerSample}, false, false, Transparency.OPAQUE, dataType);
SampleModel sampleModel = planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY
? colorModel.createCompatibleSampleModel(1, 1)
: new BandedSampleModel(dataType, 1, 1, 3, new int[]{0, 1, 2}, new int[]{0, 0, 0});
return new ImageTypeSpecifier(colorModel, sampleModel);
}
case 4:
if (bitsPerSample == 8 || bitsPerSample == 16 || bitsPerSample == 32) {
return createImageTypeSpecifier(planarConfiguration, cs, dataType, significantSamples, samplesPerPixel, true, isAlphaPremultiplied);
}
else if (bitsPerSample == 2 && planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY) {
return ImageTypeSpecifiers.createPacked(cs, 0xC0, 0x30, 0xC, 0x3, DataBuffer.TYPE_BYTE, isAlphaPremultiplied);
}
else if (bitsPerSample == 4 && planarConfiguration == TIFFBaseline.PLANARCONFIG_CHUNKY) {
return ImageTypeSpecifiers.createPacked(cs, 0xF000, 0xF00, 0xF0, 0xF, DataBuffer.TYPE_USHORT, isAlphaPremultiplied);
}
default:
throw new IIOException(String.format("Unsupported SamplesPerPixel/BitsPerSample combination for RGB TIFF (expected 3 or 4/a multiple of 2): %d/%d", samplesPerPixel, bitsPerSample));
}
case TIFFBaseline.PHOTOMETRIC_PALETTE:
// Palette
if (samplesPerPixel != 1 && !(samplesPerPixel == 2 && extraSamples != null && extraSamples.length == 1)) {
throw new IIOException("Bad SamplesPerPixel value for Palette TIFF (expected 1): " + samplesPerPixel);
}
else if (bitsPerSample <= 0 || bitsPerSample > 16) {
throw new IIOException("Bad BitsPerSample value for Palette TIFF (expected <= 16): " + bitsPerSample);
}
// NOTE: If ExtraSamples is used, PlanarConfiguration must be taken into account also for pixel data
Entry colorMap = currentIFD.getEntryById(TIFF.TAG_COLOR_MAP);
if (colorMap == null) {
throw new IIOException("Missing ColorMap for Palette TIFF");
}
IndexColorModel icm = createIndexColorModel(bitsPerSample, dataType, (int[]) colorMap.getValue());
if (extraSamples != null) {
return ImageTypeSpecifiers.createDiscreteExtraSamplesIndexedFromIndexColorModel(icm, extraSamples.length, hasAlpha);
}
return ImageTypeSpecifiers.createFromIndexColorModel(icm);
case TIFFExtension.PHOTOMETRIC_SEPARATED:
// Separated (CMYK etc)
// Consult the 332/InkSet (1=CMYK, 2=Not CMYK; see InkNames), 334/NumberOfInks (def=4) and optionally 333/InkNames
// If "Not CMYK" we'll need an ICC profile to be able to display (in a useful way), readAsRaster should still work.
int inkSet = getValueAsIntWithDefault(TIFF.TAG_INK_SET, TIFFExtension.INKSET_CMYK);
int numberOfInks = getValueAsIntWithDefault(TIFF.TAG_NUMBER_OF_INKS, 4);
// Profile must be CMYK, OR color component must match NumberOfInks
if (inkSet != TIFFExtension.INKSET_CMYK && (profile == null || profile.getNumComponents() != numberOfInks)) {
throw new IIOException(String.format(
"Embedded ICC color profile for Photometric Separated is missing or is incompatible with image data: %s != NumberOfInks (%s).",
profile != null ? profile.getNumComponents() : "null", numberOfInks));
}
if (profile != null && inkSet == TIFFExtension.INKSET_CMYK && profile.getColorSpaceType() != ColorSpace.TYPE_CMYK) {
processWarningOccurred(String.format("Embedded ICC color profile (type %s), is incompatible with image data (CMYK/type 9). Ignoring profile.", profile.getColorSpaceType()));
profile = null;
}
cs = profile == null ? ColorSpaces.getColorSpace(ColorSpaces.CS_GENERIC_CMYK) : ColorSpaces.createColorSpace(profile);
switch (significantSamples) {
case 4:
case 5:
if (bitsPerSample == 8 || bitsPerSample == 16) {
return createImageTypeSpecifier(planarConfiguration, cs, dataType, significantSamples, samplesPerPixel, significantSamples == 5, isAlphaPremultiplied);
}
default:
throw new IIOException(
String.format("Unsupported SamplesPerPixel/BitsPerSample combination for Separated TIFF (expected 4/8, 4/16, 5/8 or 5/16): %d/%s", samplesPerPixel, bitsPerSample)
);
}
case TIFFExtension.PHOTOMETRIC_CIELAB:
case TIFFExtension.PHOTOMETRIC_ICCLAB:
case TIFFExtension.PHOTOMETRIC_ITULAB:
// TODO: Would probably be more correct to handle using a CIELabColorSpace for RAW type?
// L*a*b* color. Handled using conversion to sRGB
cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
switch (planarConfiguration) {
case TIFFBaseline.PLANARCONFIG_CHUNKY:
return createImageTypeSpecifier(TIFFBaseline.PLANARCONFIG_CHUNKY, cs, dataType, 3, samplesPerPixel, false, false);
case TIFFExtension.PLANARCONFIG_PLANAR:
// TODO: Reading works fine, but we can't convert the Lab values properly yet. Need to rewrite normalizeColor
//return ImageTypeSpecifiers.createBanded(cs, new int[] {0, 1, 2}, new int[] {0, 0, 0}, dataType, false, false);
default:
throw new IIOException(
String.format("Unsupported PlanarConfiguration for Lab color TIFF (expected 1): %d", planarConfiguration)
);
}
case TIFFBaseline.PHOTOMETRIC_MASK:
// Transparency mask
// TODO: Treat as grey?
case TIFFCustom.PHOTOMETRIC_LOGL:
case TIFFCustom.PHOTOMETRIC_LOGLUV:
// Log
case TIFFCustom.PHOTOMETRIC_CFA:
case TIFFCustom.PHOTOMETRIC_LINEAR_RAW:
// RAW (DNG)
throw new IIOException("Unsupported TIFF PhotometricInterpretation value: " + interpretation);
default:
throw new IIOException("Unknown TIFF PhotometricInterpretation value: " + interpretation);
}
}
private ImageTypeSpecifier createImageTypeSpecifier(int planarConfiguration, ColorSpace cs, int dataType, int significantSamples, int samplesPerPixel, boolean alpha, boolean alphaPremultiplied) throws IIOException {
switch (planarConfiguration) {
case TIFFBaseline.PLANARCONFIG_CHUNKY:
if (samplesPerPixel > significantSamples) {
return new ImageTypeSpecifier(
new ExtraSamplesColorModel(cs, alpha, alphaPremultiplied, dataType, samplesPerPixel - significantSamples),
new PixelInterleavedSampleModel(dataType, 1, 1, samplesPerPixel, samplesPerPixel, createOffsets(samplesPerPixel)));
}
return ImageTypeSpecifiers.createInterleaved(cs, createOffsets(significantSamples), dataType, alpha, alphaPremultiplied);
case TIFFExtension.PLANARCONFIG_PLANAR:
return ImageTypeSpecifiers.createBanded(cs, createOffsets(significantSamples), new int[significantSamples], dataType, alpha, alphaPremultiplied);
default:
throw new IIOException(String.format("Unsupported PlanarConfiguration (expected 1 or 2): %d", planarConfiguration));
}
}
private static int[] createOffsets(int samplesPerPixel) {
int[] offsets = new int[samplesPerPixel];
for (int i = 0; i < samplesPerPixel; i++) {
offsets[i] = i;
}
return offsets;
}
private int getPhotometricInterpretationWithFallback() throws IIOException {
// PhotometricInterpretation is a required tag, but as it can be guessed this does a fallback that is similar to JAI ImageIO.
int interpretation = getValueAsIntWithDefault(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, "PhotometricInterpretation", -1);
if (interpretation == -1) {
int compression = getValueAsIntWithDefault(TIFF.TAG_COMPRESSION, TIFFBaseline.COMPRESSION_NONE);
int samplesPerPixel = getValueAsIntWithDefault(TIFF.TAG_SAMPLES_PER_PIXEL, 1);
Entry extraSamples = currentIFD.getEntryById(TIFF.TAG_EXTRA_SAMPLES);
Entry colorMap = currentIFD.getEntryById(TIFF.TAG_COLOR_MAP);
interpretation = guessPhotometricInterpretation(compression, samplesPerPixel, extraSamples, colorMap);
processWarningOccurred("Missing PhotometricInterpretation, determining fallback: " + interpretation);
}
return interpretation;
}
static int guessPhotometricInterpretation(int compression, int samplesPerPixel, Entry extraSamples, Entry colorMap) {
int extraSamplesCount = extraSamples == null ? 0 : extraSamples.valueCount();
if (compression == TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE
|| compression == TIFFExtension.COMPRESSION_CCITT_T4
|| compression == TIFFExtension.COMPRESSION_CCITT_T6) {
return TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO;
}
else if (colorMap != null) {
return TIFFBaseline.PHOTOMETRIC_PALETTE;
}
else if ((samplesPerPixel - extraSamplesCount) == 3) {
if (compression == TIFFExtension.COMPRESSION_JPEG
|| compression == TIFFExtension.COMPRESSION_OLD_JPEG) {
return TIFFExtension.PHOTOMETRIC_YCBCR;
}
else {
return TIFFBaseline.PHOTOMETRIC_RGB;
}
}
else if ((samplesPerPixel - extraSamplesCount) == 4) {
return TIFFExtension.PHOTOMETRIC_SEPARATED;
}
else {
return TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO;
}
}
private int getOpaqueSamplesPerPixel(final int photometricInterpretation) throws IIOException {
switch (photometricInterpretation) {
case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO:
case TIFFBaseline.PHOTOMETRIC_PALETTE:
case TIFFBaseline.PHOTOMETRIC_MASK:
return 1;
case TIFFBaseline.PHOTOMETRIC_RGB:
case TIFFExtension.PHOTOMETRIC_YCBCR:
case TIFFExtension.PHOTOMETRIC_CIELAB:
case TIFFExtension.PHOTOMETRIC_ICCLAB:
case TIFFExtension.PHOTOMETRIC_ITULAB:
return 3;
case TIFFExtension.PHOTOMETRIC_SEPARATED:
return getValueAsIntWithDefault(TIFF.TAG_NUMBER_OF_INKS, 4);
case TIFFCustom.PHOTOMETRIC_LOGL:
case TIFFCustom.PHOTOMETRIC_LOGLUV:
case TIFFCustom.PHOTOMETRIC_CFA:
case TIFFCustom.PHOTOMETRIC_LINEAR_RAW:
throw new IIOException("Unsupported TIFF PhotometricInterpretation value: " + photometricInterpretation);
default:
throw new IIOException("Unknown TIFF PhotometricInterpretation value: " + photometricInterpretation);
}
}
private int getDataType(int sampleFormat, int bitsPerSample) throws IIOException {
switch (sampleFormat) {
case TIFFExtension.SAMPLEFORMAT_UNDEFINED:
// Spec says:
// A field value of “undefined” is a statement by the writer that it did not know how
// to interpret the data samples; for example, if it were copying an existing image. A
// reader would typically treat an image with “undefined” data as if the field were
// not present (i.e. as unsigned integer data).
case TIFFBaseline.SAMPLEFORMAT_UINT:
return bitsPerSample <= 8 ? DataBuffer.TYPE_BYTE : bitsPerSample <= 16 ? DataBuffer.TYPE_USHORT : DataBuffer.TYPE_INT;
case TIFFExtension.SAMPLEFORMAT_INT:
switch (bitsPerSample) {
case 8:
return DataBuffer.TYPE_BYTE;
case 16:
return DataBuffer.TYPE_SHORT;
case 32:
return DataBuffer.TYPE_INT;
}
throw new IIOException("Unsupported BitsPerSample for SampleFormat 2/Signed Integer (expected 8/16/32): " + bitsPerSample);
case TIFFExtension.SAMPLEFORMAT_FP:
if (bitsPerSample == 16 || bitsPerSample == 32) {
return DataBuffer.TYPE_FLOAT;
}
throw new IIOException("Unsupported BitsPerSample for SampleFormat 3/Floating Point (expected 16/32): " + bitsPerSample);
default:
throw new IIOException("Unknown TIFF SampleFormat (expected 1, 2, 3 or 4): " + sampleFormat);
}
}
private IndexColorModel createIndexColorModel(final int bitsPerSample, final int dataType, final int[] cmapShort) {
// According to the spec, there should be exactly 3 * bitsPerSample^2 entries in the color map for TIFF.
// Should we enforce this?
int[] cmap = new int[cmapShort.length / 3];
// We'll detect whether the color map data is 8 bit, rather than 16 bit while converting
boolean cmapIs8Bit = true;
// All reds, then greens, and finally blues
for (int i = 0; i < cmap.length; i++) {
cmap[i] = (cmapShort[i ] / 256) << 16
| (cmapShort[i + cmap.length] / 256) << 8
| (cmapShort[i + 2 * cmap.length] / 256);
if (cmapIs8Bit && cmap[i] != 0) {
cmapIs8Bit = false;
}
}
if (cmapIs8Bit) {
// This color map is using only the lower 8 bits, making the image all black.
// We'll create a new color map, based on the non-scaled 8 bit values.
processWarningOccurred("8 bit ColorMap detected.");
// All reds, then greens, and finally blues
for (int i = 0; i < cmap.length; i++) {
cmap[i] = (cmapShort[i ]) << 16
| (cmapShort[i + cmap.length]) << 8
| (cmapShort[i + 2 * cmap.length]);
}
}
return new IndexColorModel(bitsPerSample, cmap.length, cmap, 0, false, -1, dataType);
}
private int getSampleFormat() throws IIOException {
long[] value = getValueAsLongArray(TIFF.TAG_SAMPLE_FORMAT, "SampleFormat", false);
if (value != null) {
long sampleFormat = value[0];
for (int i = 1; i < value.length; i++) {
if (value[i] != sampleFormat) {
throw new IIOException("Variable TIFF SampleFormat not supported: " + Arrays.toString(value));
}
}
return (int) sampleFormat;
}
// The default
return TIFFBaseline.SAMPLEFORMAT_UINT;
}
private int getBitsPerSample() throws IIOException {
long[] value = getValueAsLongArray(TIFF.TAG_BITS_PER_SAMPLE, "BitsPerSample", false);
if (value == null || value.length == 0) {
return 1;
}
else {
int bitsPerSample = (int) value[0];
if (value.length == 3 && (value[0] == 5 && value[1] == 6 && value[2] == 5)) {
// Special case for UINT_565. We're good.
}
else {
for (int i = 1; i < value.length; i++) {
if (value[i] != bitsPerSample) {
throw new IIOException("Variable BitsPerSample not supported: " + Arrays.toString(value));
}
}
}
return bitsPerSample;
}
}
@Override
public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException {
readIFD(imageIndex);
ImageTypeSpecifier rawType = getRawImageType(imageIndex);
Set<ImageTypeSpecifier> specs = new LinkedHashSet<>(5);
// TODO: Based on raw type, we can probably convert to most RGB types at least, maybe gray etc
if (rawType.getColorModel().getColorSpace().isCS_sRGB()) {
if (rawType.getNumBands() == 3 && rawType.getBitsPerBand(0) == 8) {
specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_3BYTE_BGR));
// specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_BGR));
// specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB));
}
else if (rawType.getNumBands() == 4 && rawType.getBitsPerBand(0) == 8) {
specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_4BYTE_ABGR));
// specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB));
specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_4BYTE_ABGR_PRE));
}
}
specs.add(rawType);
return specs.iterator();
}
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
readIFD(imageIndex);
int width = getWidth(imageIndex);
int height = getHeight(imageIndex);
BufferedImage destination = getDestination(param, getImageTypes(imageIndex), width, height);
ImageTypeSpecifier rawType = getRawImageType(imageIndex);
checkReadParamBandSettings(param, rawType.getNumBands(), destination.getSampleModel().getNumBands());
final Rectangle srcRegion = new Rectangle();
final Rectangle dstRegion = new Rectangle();
computeRegions(param, width, height, destination, srcRegion, dstRegion);
int xSub = param != null ? param.getSourceXSubsampling() : 1;
int ySub = param != null ? param.getSourceYSubsampling() : 1;
WritableRaster destRaster = clipToRect(destination.getRaster(), dstRegion, param != null ? param.getDestinationBands() : null);
final int interpretation = getPhotometricInterpretationWithFallback();
final int compression = getValueAsIntWithDefault(TIFF.TAG_COMPRESSION, TIFFBaseline.COMPRESSION_NONE);
final int predictor = getValueAsIntWithDefault(TIFF.TAG_PREDICTOR, 1);
final int planarConfiguration = getValueAsIntWithDefault(TIFF.TAG_PLANAR_CONFIGURATION, TIFFBaseline.PLANARCONFIG_CHUNKY);
final int samplesInTile = planarConfiguration == TIFFExtension.PLANARCONFIG_PLANAR ? 1 : rawType.getNumBands();
// NOTE: We handle strips as tiles of tileWidth == width by tileHeight == rowsPerStrip
// Strips are top/down, tiles are left/right, top/down
int stripTileWidth = width;
long rowsPerStrip = getValueAsLongWithDefault(TIFF.TAG_ROWS_PER_STRIP, (long) Integer.MAX_VALUE);
int stripTileHeight = rowsPerStrip < height ? (int) rowsPerStrip : height;
long[] stripTileOffsets = getValueAsLongArray(TIFF.TAG_TILE_OFFSETS, "TileOffsets", false);
long[] stripTileByteCounts;
if (stripTileOffsets != null) {
stripTileByteCounts = getValueAsLongArray(TIFF.TAG_TILE_BYTE_COUNTS, "TileByteCounts", false);
if (stripTileByteCounts == null) {
processWarningOccurred("Missing TileByteCounts for tiled TIFF with compression: " + compression);
}
else if (stripTileByteCounts.length == 0 || containsZero(stripTileByteCounts)) {
stripTileByteCounts = null;
processWarningOccurred("Ignoring all-zero TileByteCounts for tiled TIFF with compression: " + compression);
}
stripTileWidth = getValueAsInt(TIFF.TAG_TILE_WIDTH, "TileWidth");
stripTileHeight = getValueAsInt(TIFF.TAG_TILE_HEIGTH, "TileHeight");
}
else {
stripTileOffsets = getValueAsLongArray(TIFF.TAG_STRIP_OFFSETS, "StripOffsets", true);
stripTileByteCounts = getValueAsLongArray(TIFF.TAG_STRIP_BYTE_COUNTS, "StripByteCounts", false);
if (stripTileByteCounts == null) {
processWarningOccurred("Missing StripByteCounts for TIFF with compression: " + compression);
}
else if (stripTileByteCounts.length == 0 || containsZero(stripTileByteCounts)) {
stripTileByteCounts = null;
processWarningOccurred("Ignoring all-zero StripByteCounts for TIFF with compression: " + compression);
}
// NOTE: This is really against the spec, but libTiff seems to handle it. TIFF 6.0 says:
// "Do not use both strip- oriented and tile-oriented fields in the same TIFF file".
stripTileWidth = getValueAsIntWithDefault(TIFF.TAG_TILE_WIDTH, "TileWidth", stripTileWidth);
stripTileHeight = getValueAsIntWithDefault(TIFF.TAG_TILE_HEIGTH, "TileHeight", stripTileHeight);
}
int tilesAcross = (width + stripTileWidth - 1) / stripTileWidth;
int tilesDown = (height + stripTileHeight - 1) / stripTileHeight;
// Raw type may contain extra samples
WritableRaster rowRaster = rawType.createBufferedImage(stripTileWidth, 1).getRaster();