-
Notifications
You must be signed in to change notification settings - Fork 242
/
TiffParser.java
1450 lines (1255 loc) · 47 KB
/
TiffParser.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
/*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2017 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
*
* 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 HOLDERS 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.
* #L%
*/
package loci.formats.tiff;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import loci.common.ByteArrayHandle;
import loci.common.Constants;
import loci.common.DataTools;
import loci.common.RandomAccessInputStream;
import loci.common.Region;
import loci.common.enumeration.EnumException;
import loci.formats.FormatException;
import loci.formats.ImageTools;
import loci.formats.codec.CodecOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Parses TIFF data from an input source.
*
* @author Curtis Rueden ctrueden at wisc.edu
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Chris Allan callan at blackcat.ca
*/
public class TiffParser implements Closeable {
// -- Constants --
private static final Logger LOGGER =
LoggerFactory.getLogger(TiffParser.class);
// -- Fields --
/** Input source from which to parse TIFF data. */
protected transient RandomAccessInputStream in;
/** Cached tile buffer to avoid re-allocations when reading tiles. */
private byte[] cachedTileBuffer;
/** Whether or not the TIFF file contains BigTIFF data. */
private boolean bigTiff;
/** Whether or not 64-bit offsets are used for non-BigTIFF files. */
private boolean fakeBigTiff = false;
private boolean ycbcrCorrection = true;
private boolean equalStrips = false;
private boolean doCaching;
/** Cached list of IFDs in the current file. */
private IFDList ifdList;
/** Cached first IFD in the current file. */
private IFD firstIFD;
/** Codec options to be used when decoding compressed pixel data. */
private CodecOptions codecOptions = CodecOptions.getDefaultOptions();
private boolean canClose = false;
// -- Constructors --
/** Constructs a new TIFF parser from the given file name. */
public TiffParser(String filename) throws IOException {
this(new RandomAccessInputStream(filename));
canClose = true;
}
/** Constructs a new TIFF parser from the given input source. */
public TiffParser(RandomAccessInputStream in) {
this.in = in;
doCaching = true;
try {
long fp = in.getFilePointer();
checkHeader();
in.seek(fp);
}
catch (IOException e) { }
}
// -- Closeable methods --
/**
* Close the underlying stream, if this TiffParser was constructed
* with a file path. Closing a stream that was pre-initialized
* is potentially dangerous.
*/
@Override
public void close() throws IOException {
if (canClose && in != null) {
in.close();
}
}
// -- TiffParser methods --
/**
* Sets whether or not to assume that strips are of equal size.
* @param equalStrips Whether or not the strips are of equal size.
*/
public void setAssumeEqualStrips(boolean equalStrips) {
this.equalStrips = equalStrips;
}
/**
* Sets the codec options to be used when decompressing pixel data.
* @param codecOptions Codec options to use.
*/
public void setCodecOptions(CodecOptions codecOptions) {
this.codecOptions = codecOptions;
}
/**
* Retrieves the current set of codec options being used to decompress pixel
* data.
* @return See above.
*/
public CodecOptions getCodecOptions() {
return codecOptions;
}
/** Sets whether or not IFD entries should be cached. */
public void setDoCaching(boolean doCaching) {
this.doCaching = doCaching;
}
/** Sets whether or not 64-bit offsets are used for non-BigTIFF files. */
public void setUse64BitOffsets(boolean use64Bit) {
fakeBigTiff = use64Bit;
}
/** Sets whether or not YCbCr color correction is allowed. */
public void setYCbCrCorrection(boolean correctionAllowed) {
ycbcrCorrection = correctionAllowed;
}
/** Gets the stream from which TIFF data is being parsed. */
public RandomAccessInputStream getStream() {
return in;
}
/** Tests this stream to see if it represents a TIFF file. */
public boolean isValidHeader() {
try {
return checkHeader() != null;
}
catch (IOException e) {
return false;
}
}
/**
* Checks the TIFF header.
*
* @return true if little-endian,
* false if big-endian,
* or null if not a TIFF.
*/
public Boolean checkHeader() throws IOException {
if (in.length() < 4) return null;
// byte order must be II or MM
in.seek(0);
int endianOne = in.read();
int endianTwo = in.read();
boolean littleEndian = endianOne == TiffConstants.LITTLE &&
endianTwo == TiffConstants.LITTLE; // II
boolean bigEndian = endianOne == TiffConstants.BIG &&
endianTwo == TiffConstants.BIG; // MM
if (!littleEndian && !bigEndian) return null;
// check magic number (42)
in.order(littleEndian);
short magic = in.readShort();
bigTiff = magic == TiffConstants.BIG_TIFF_MAGIC_NUMBER;
if (magic != TiffConstants.MAGIC_NUMBER &&
magic != TiffConstants.BIG_TIFF_MAGIC_NUMBER)
{
return null;
}
return Boolean.valueOf(littleEndian);
}
/** Returns whether or not the current TIFF file contains BigTIFF data. */
public boolean isBigTiff() {
return bigTiff;
}
// -- TiffParser methods - IFD parsing --
/** Returns the main list of IFDs in the file.
*
* This does not include SUBIFDS.
*/
public IFDList getMainIFDs() throws IOException {
if (ifdList != null) return ifdList;
long[] offsets = getIFDOffsets();
IFDList ifds = new IFDList();
for (long offset : offsets) {
IFD ifd = getIFD(offset);
if (ifd == null) continue;
if (ifd.containsKey(IFD.IMAGE_WIDTH)) {
ifds.add(ifd);
}
}
if (doCaching) {
ifdList = ifds;
}
return ifds;
}
/** Returns the SUBIFDS belonging to a given IFD. */
public IFDList getSubIFDs(IFD ifd) throws IOException {
IFDList list = new IFDList();
long[] offsets = null;
try {
fillInIFD(ifd);
offsets = ifd.getIFDLongArray(IFD.SUB_IFD);
} catch (FormatException e) {
}
if (offsets != null) {
for (long offset : offsets) {
list.add(getIFD(offset));
}
}
return list;
}
/** Returns all IFDs in the file, including SUBIFDS.
* @deprecated Use {@link #getMainIFDs()} and {@link #getSubIFDs(IFD)} instead.
*/
@Deprecated
public IFDList getIFDs() throws IOException {
if (ifdList != null) return ifdList;
long[] offsets = getIFDOffsets();
IFDList ifds = new IFDList();
for (long offset : offsets) {
IFD ifd = getIFD(offset);
if (ifd == null) continue;
if (ifd.containsKey(IFD.IMAGE_WIDTH)) ifds.add(ifd);
long[] subOffsets = null;
try {
if (!doCaching && ifd.containsKey(IFD.SUB_IFD)) {
fillInIFD(ifd);
}
subOffsets = ifd.getIFDLongArray(IFD.SUB_IFD);
}
catch (FormatException e) { }
if (subOffsets != null) {
for (long subOffset : subOffsets) {
IFD sub = getIFD(subOffset);
if (sub != null) {
ifds.add(sub);
}
}
}
}
if (doCaching) ifdList = ifds;
return ifds;
}
/** Returns thumbnail IFDs. */
public IFDList getThumbnailIFDs() throws IOException {
IFDList ifds = getMainIFDs();
IFDList thumbnails = new IFDList();
for (IFD ifd : ifds) {
Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE);
int subfileType = subfile == null ? 0 : subfile.intValue();
if (subfileType == 1) {
thumbnails.add(ifd);
}
}
return thumbnails;
}
/** Returns non-thumbnail IFDs. */
public IFDList getNonThumbnailIFDs() throws IOException {
IFDList ifds = getMainIFDs();
IFDList nonThumbs = new IFDList();
for (IFD ifd : ifds) {
Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE);
int subfileType = subfile == null ? 0 : subfile.intValue();
if (subfileType != 1 || ifds.size() <= 1) {
nonThumbs.add(ifd);
}
}
return nonThumbs;
}
/** Returns EXIF IFDs. */
public IFDList getExifIFDs() throws FormatException, IOException {
IFDList ifds = getMainIFDs();
IFDList exif = new IFDList();
for (IFD ifd : ifds) {
long offset = ifd.getIFDLongValue(IFD.EXIF, 0);
if (offset != 0) {
IFD exifIFD = getIFD(offset);
if (exifIFD != null) {
exif.add(exifIFD);
}
}
}
return exif;
}
/** Gets the offsets to every IFD in the file. */
public long[] getIFDOffsets() throws IOException {
// check TIFF header
int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY :
TiffConstants.BYTES_PER_ENTRY;
final List<Long> offsets = new ArrayList<Long>();
long offset = getFirstOffset();
while (offset > 0 && offset < in.length()) {
in.seek(offset);
offsets.add(offset);
long nEntries = bigTiff ? in.readLong() : in.readUnsignedShort();
long entryBytes = nEntries * bytesPerEntry;
if (in.getFilePointer() + entryBytes + (bigTiff ? 8 : 4) > in.length()) {
// this can easily happen when writing multiple planes to a file
break;
}
in.skipBytes(entryBytes);
offset = getNextOffset(offset);
}
long[] f = new long[offsets.size()];
for (int i=0; i<f.length; i++) {
f[i] = offsets.get(i).longValue();
}
return f;
}
/**
* Gets the first IFD within the TIFF file, or null
* if the input source is not a valid TIFF file.
*/
public IFD getFirstIFD() throws IOException {
if (firstIFD != null) return firstIFD;
long offset = getFirstOffset();
IFD ifd = getIFD(offset);
if (doCaching) firstIFD = ifd;
return ifd;
}
/**
* Retrieve a given entry from the first IFD in the stream.
*
* @param tag the tag of the entry to be retrieved.
* @return an object representing the entry's fields.
* @throws IOException when there is an error accessing the stream.
* @throws IllegalArgumentException when the tag number is unknown.
*/
// TODO : Try to remove this method. It is only being used by
// loci.formats.in.MetamorphReader.
public TiffIFDEntry getFirstIFDEntry(int tag) throws IOException {
// Get the offset of the first IFD
long offset = getFirstOffset();
if (offset < 0) return null;
// The following loosely resembles the logic of getIFD()...
in.seek(offset);
long numEntries = bigTiff ? in.readLong() : in.readUnsignedShort();
for (int i = 0; i < numEntries; i++) {
in.seek(offset + // The beginning of the IFD
(bigTiff ? 8 : 2) + // The width of the initial numEntries field
(bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY :
TiffConstants.BYTES_PER_ENTRY) * i);
TiffIFDEntry entry = readTiffIFDEntry();
if (entry.getTag() == tag) {
return entry;
}
}
throw new IllegalArgumentException("Unknown tag: " + tag);
}
/**
* Gets offset to the first IFD, or -1 if stream is not TIFF.
*/
public long getFirstOffset() throws IOException {
Boolean header = checkHeader();
if (header == null) return -1;
if (bigTiff) in.skipBytes(4);
return getNextOffset(0);
}
/** Gets the IFD stored at the given offset. */
public IFD getIFD(long offset) throws IOException {
if (offset < 0 || offset >= in.length()) return null;
IFD ifd = new IFD();
// save little-endian flag to internal LITTLE_ENDIAN tag
ifd.put(Integer.valueOf(IFD.LITTLE_ENDIAN), Boolean.valueOf(in.isLittleEndian()));
ifd.put(Integer.valueOf(IFD.BIG_TIFF), Boolean.valueOf(bigTiff));
// read in directory entries for this IFD
LOGGER.trace("getIFD: seeking IFD at {}", offset);
in.seek(offset);
long numEntries = bigTiff ? in.readLong() : in.readUnsignedShort();
LOGGER.trace("getIFD: {} directory entries to read", numEntries);
if (numEntries == 0 || numEntries == 1) return ifd;
int bytesPerEntry = bigTiff ?
TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY;
int baseOffset = bigTiff ? 8 : 2;
for (int i=0; i<numEntries; i++) {
in.seek(offset + baseOffset + bytesPerEntry * i);
TiffIFDEntry entry = null;
try {
entry = readTiffIFDEntry();
}
catch (EnumException e) {
LOGGER.debug("", e);
}
if (entry == null) break;
int count = entry.getValueCount();
int tag = entry.getTag();
long pointer = entry.getValueOffset();
int bpe = entry.getType().getBytesPerElement();
if (count < 0 || bpe <= 0) {
// invalid data
in.skipBytes(bytesPerEntry - 4 - (bigTiff ? 8 : 4));
continue;
}
Object value = null;
long inputLen = in.length();
if (count * bpe + pointer > inputLen) {
int oldCount = count;
count = (int) ((inputLen - pointer) / bpe);
LOGGER.trace("getIFD: truncated {} array elements for tag {}",
(oldCount - count), tag);
if (count < 0) count = oldCount;
}
if (count < 0 || count > in.length()) break;
if (pointer != in.getFilePointer() && !doCaching) {
value = entry;
}
else value = getIFDValue(entry);
if (value != null && !ifd.containsKey(Integer.valueOf(tag))) {
ifd.put(Integer.valueOf(tag), value);
}
}
long newOffset =offset + baseOffset + bytesPerEntry * numEntries;
if (newOffset < in.length()) {
in.seek(newOffset);
}
else {
in.seek(in.length());
}
return ifd;
}
/** Fill in IFD entries that are stored at an arbitrary offset. */
public void fillInIFD(IFD ifd) throws IOException {
HashSet<TiffIFDEntry> entries = new HashSet<TiffIFDEntry>();
for (Object key : ifd.keySet()) {
if (ifd.get(key) instanceof TiffIFDEntry) {
entries.add((TiffIFDEntry) ifd.get(key));
}
}
for (TiffIFDEntry entry : entries) {
if ((entry.getValueCount() < 10 * 1024 * 1024 || entry.getTag() < 32768) &&
entry.getTag() != IFD.COLOR_MAP)
{
ifd.put(Integer.valueOf(entry.getTag()), getIFDValue(entry));
}
}
}
/** Retrieve the value corresponding to the given TiffIFDEntry. */
public Object getIFDValue(TiffIFDEntry entry) throws IOException {
IFDType type = entry.getType();
int count = entry.getValueCount();
long offset = entry.getValueOffset();
LOGGER.trace("Reading entry {} from {}; type={}, count={}",
new Object[] {entry.getTag(), offset, type, count});
if (offset >= in.length()) {
return null;
}
if (offset != in.getFilePointer()) {
if (fakeBigTiff && offset < 0) {
offset &= 0xffffffffL;
offset += 0x100000000L;
}
if (offset >= in.length()) {
return null;
}
in.seek(offset);
}
if (type == IFDType.BYTE) {
// 8-bit unsigned integer
if (count == 1) return in.readUnsignedByte();
byte[] bytes = new byte[count];
in.readFully(bytes);
// bytes are unsigned, so use shorts
short[] shorts = new short[count];
for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff);
return shorts;
}
else if (type == IFDType.ASCII) {
// 8-bit byte that contain a 7-bit ASCII code;
// the last byte must be NUL (binary zero)
byte[] ascii = new byte[count];
in.read(ascii);
// count number of null terminators
int nullCount = 0;
for (int j=0; j<count; j++) {
if (ascii[j] == 0 || j == count - 1) nullCount++;
}
// convert character array to array of strings
String[] strings = nullCount == 1 ? null : new String[nullCount];
String s = null;
int c = 0, ndx = -1;
for (int j=0; j<count; j++) {
if (ascii[j] == 0) {
s = new String(ascii, ndx + 1, j - ndx - 1, Constants.ENCODING);
ndx = j;
}
else if (j == count - 1) {
// handle non-null-terminated strings
s = new String(ascii, ndx + 1, j - ndx, Constants.ENCODING);
}
else s = null;
if (strings != null && s != null) strings[c++] = s;
}
return strings == null ? (Object) s : strings;
}
else if (type == IFDType.SHORT) {
// 16-bit (2-byte) unsigned integer
if (count == 1) return Integer.valueOf(in.readUnsignedShort());
int[] shorts = new int[count];
for (int j=0; j<count; j++) {
shorts[j] = in.readUnsignedShort();
}
return shorts;
}
else if (type == IFDType.LONG || type == IFDType.IFD) {
// 32-bit (4-byte) unsigned integer
if (count == 1) return Long.valueOf(in.readUnsignedInt());
long[] longs = new long[count];
for (int j=0; j<count; j++) {
if (in.getFilePointer() + 4 <= in.length()) {
longs[j] = in.readUnsignedInt();
}
}
return longs;
}
else if (type == IFDType.LONG8 || type == IFDType.SLONG8
|| type == IFDType.IFD8) {
if (count == 1) return Long.valueOf(in.readLong());
long[] longs = null;
if (equalStrips && (entry.getTag() == IFD.STRIP_BYTE_COUNTS ||
entry.getTag() == IFD.TILE_BYTE_COUNTS))
{
longs = new long[1];
longs[0] = in.readLong();
}
else if (entry.getTag() == IFD.STRIP_OFFSETS ||
entry.getTag() == IFD.TILE_OFFSETS ||
entry.getTag() == IFD.STRIP_BYTE_COUNTS ||
entry.getTag() == IFD.TILE_BYTE_COUNTS)
{
OnDemandLongArray offsets = new OnDemandLongArray(in);
offsets.setSize(count);
return offsets;
}
else {
longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readLong();
}
return longs;
}
else if (type == IFDType.RATIONAL || type == IFDType.SRATIONAL) {
// Two LONGs or SLONGs: the first represents the numerator
// of a fraction; the second, the denominator
if (count == 1) return new TiffRational(in.readUnsignedInt(), in.readUnsignedInt());
TiffRational[] rationals = new TiffRational[count];
for (int j=0; j<count; j++) {
rationals[j] = new TiffRational(in.readUnsignedInt(), in.readUnsignedInt());
}
return rationals;
}
else if (type == IFDType.SBYTE || type == IFDType.UNDEFINED) {
// SBYTE: An 8-bit signed (twos-complement) integer
// UNDEFINED: An 8-bit byte that may contain anything,
// depending on the definition of the field
if (count == 1) return Byte.valueOf(in.readByte());
byte[] sbytes = new byte[count];
in.read(sbytes);
return sbytes;
}
else if (type == IFDType.SSHORT) {
// A 16-bit (2-byte) signed (twos-complement) integer
if (count == 1) return Short.valueOf(in.readShort());
short[] sshorts = new short[count];
for (int j=0; j<count; j++) sshorts[j] = in.readShort();
return sshorts;
}
else if (type == IFDType.SLONG) {
// A 32-bit (4-byte) signed (twos-complement) integer
if (count == 1) return Integer.valueOf(in.readInt());
int[] slongs = new int[count];
for (int j=0; j<count; j++) slongs[j] = in.readInt();
return slongs;
}
else if (type == IFDType.FLOAT) {
// Single precision (4-byte) IEEE format
if (count == 1) return Float.valueOf(in.readFloat());
float[] floats = new float[count];
for (int j=0; j<count; j++) floats[j] = in.readFloat();
return floats;
}
else if (type == IFDType.DOUBLE) {
// Double precision (8-byte) IEEE format
if (count == 1) return Double.valueOf(in.readDouble());
double[] doubles = new double[count];
for (int j=0; j<count; j++) {
doubles[j] = in.readDouble();
}
return doubles;
}
return null;
}
/** Convenience method for obtaining a stream's first ImageDescription. */
public String getComment() throws IOException {
IFD firstIFD = getFirstIFD();
if (firstIFD == null) {
return null;
}
fillInIFD(firstIFD);
return firstIFD.getComment();
}
/**
* Retrieve the color map associated with the given IFD.
*/
public int[] getColorMap(IFD ifd) throws IOException {
Object map = ifd.get(IFD.COLOR_MAP);
if (map == null) {
return null;
}
int[] colorMap = null;
if (map instanceof TiffIFDEntry) {
colorMap = (int[]) getIFDValue((TiffIFDEntry) map);
}
else if (map instanceof int[]) {
colorMap = (int[]) map;
}
return colorMap;
}
// -- TiffParser methods - image reading --
public byte[] getTile(IFD ifd, byte[] buf, int row, int col)
throws FormatException, IOException
{
byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES);
codecOptions.interleaved = true;
codecOptions.littleEndian = ifd.isLittleEndian();
long tileWidth = ifd.getTileWidth();
long tileLength = ifd.getTileLength();
int samplesPerPixel = ifd.getSamplesPerPixel();
int planarConfig = ifd.getPlanarConfiguration();
TiffCompression compression = ifd.getCompression();
long numTileCols = ifd.getTilesPerRow();
int pixel = ifd.getBytesPerSample()[0];
int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel;
if (ifd.get(IFD.STRIP_BYTE_COUNTS) instanceof OnDemandLongArray) {
OnDemandLongArray counts = (OnDemandLongArray) ifd.get(IFD.STRIP_BYTE_COUNTS);
if (counts != null) {
counts.setStream(in);
}
}
if (ifd.get(IFD.TILE_BYTE_COUNTS) instanceof OnDemandLongArray) {
OnDemandLongArray counts = (OnDemandLongArray) ifd.get(IFD.TILE_BYTE_COUNTS);
if (counts != null) {
counts.setStream(in);
}
}
long[] stripByteCounts = ifd.getStripByteCounts();
long[] rowsPerStrip = ifd.getRowsPerStrip();
int offsetIndex = (int) (row * numTileCols + col);
int countIndex = offsetIndex;
if (equalStrips) {
countIndex = 0;
}
if (stripByteCounts[countIndex] == (rowsPerStrip[0] * tileWidth) &&
pixel > 1)
{
stripByteCounts[countIndex] *= pixel;
}
else if (stripByteCounts[countIndex] < 0 && countIndex > 0) {
LOGGER.debug("byte count #{} was {}; correcting to {}", countIndex,
stripByteCounts[countIndex], stripByteCounts[countIndex - 1]);
stripByteCounts[countIndex] = stripByteCounts[countIndex - 1];
}
long stripOffset = 0;
long nStrips = 0;
if (ifd.getOnDemandStripOffsets() != null) {
OnDemandLongArray stripOffsets = ifd.getOnDemandStripOffsets();
stripOffsets.setStream(in);
stripOffset = stripOffsets.get(offsetIndex);
nStrips = stripOffsets.size();
}
else {
long[] stripOffsets = ifd.getStripOffsets();
stripOffset = stripOffsets[offsetIndex];
nStrips = stripOffsets.length;
}
int size = (int) (tileWidth * tileLength * pixel * effectiveChannels);
if (buf == null) buf = new byte[size];
if (stripByteCounts[countIndex] == 0 || stripOffset >= in.length()) {
// make sure that the buffer is cleared before returning
// the caller may be reusing the same buffer for multiple calls to getTile
Arrays.fill(buf, (byte) 0);
return buf;
}
int tileSize = (int) stripByteCounts[countIndex];
if (jpegTable != null) {
tileSize += jpegTable.length - 2;
}
byte[] tile = new byte[tileSize];
LOGGER.debug("Reading tile Length {} Offset {}", tile.length, stripOffset);
if (jpegTable != null) {
System.arraycopy(jpegTable, 0, tile, 0, jpegTable.length - 2);
in.seek(stripOffset + 2);
in.read(tile, jpegTable.length - 2, tile.length - (jpegTable.length - 2));
}
else {
in.seek(stripOffset);
in.read(tile);
}
// reverse bits in each byte if FillOrder == 2
if (ifd.getIFDIntValue(IFD.FILL_ORDER) == 2 &&
(compression.getCode() <= TiffCompression.GROUP_4_FAX.getCode() ||
compression.getCode() == TiffCompression.DEFLATE.getCode() ||
compression.getCode() == TiffCompression.PROPRIETARY_DEFLATE.getCode()))
{
for (int i=0; i<tile.length; i++) {
tile[i] = (byte) (Integer.reverse(tile[i]) >> 24);
}
}
codecOptions.maxBytes = (int) Math.max(size, tile.length);
codecOptions.ycbcr =
ifd.getPhotometricInterpretation() == PhotoInterp.Y_CB_CR &&
ifd.getIFDIntValue(IFD.Y_CB_CR_SUB_SAMPLING) == 1 && ycbcrCorrection;
tile = compression.decompress(tile, codecOptions);
TiffCompression.undifference(tile, ifd);
unpackBytes(buf, 0, tile, ifd);
if (planarConfig == 2 && !ifd.isTiled() && ifd.getSamplesPerPixel() > 1) {
int channel = (int) (row % nStrips);
if (channel < ifd.getBytesPerSample().length) {
int realBytes = ifd.getBytesPerSample()[channel];
if (realBytes != pixel) {
// re-pack pixels to account for differing bits per sample
boolean littleEndian = ifd.isLittleEndian();
int[] samples = new int[buf.length / pixel];
for (int i=0; i<samples.length; i++) {
samples[i] =
DataTools.bytesToInt(buf, i * realBytes, realBytes, littleEndian);
}
for (int i=0; i<samples.length; i++) {
DataTools.unpackBytes(
samples[i], buf, i * pixel, pixel, littleEndian);
}
}
}
}
return buf;
}
public byte[] getSamples(IFD ifd, byte[] buf)
throws FormatException, IOException
{
long width = ifd.getImageWidth();
long length = ifd.getImageLength();
return getSamples(ifd, buf, 0, 0, width, length);
}
public byte[] getSamples(IFD ifd, byte[] buf, int x, int y,
long width, long height) throws FormatException, IOException
{
return getSamples(ifd, buf, x, y, width, height, 0, 0);
}
public byte[] getSamples(IFD ifd, byte[] buf, int x, int y,
long width, long height, int overlapX, int overlapY)
throws FormatException, IOException
{
LOGGER.trace("parsing IFD entries");
// get internal non-IFD entries
boolean littleEndian = ifd.isLittleEndian();
in.order(littleEndian);
// get relevant IFD entries
int samplesPerPixel = ifd.getSamplesPerPixel();
long tileWidth = ifd.getTileWidth();
long tileLength = ifd.getTileLength();
if (tileLength <= 0) {
LOGGER.trace("Tile length is {}; setting it to {}", tileLength, height);
tileLength = height;
}
long numTileRows = ifd.getTilesPerColumn();
long numTileCols = ifd.getTilesPerRow();
PhotoInterp photoInterp = ifd.getPhotometricInterpretation();
int planarConfig = ifd.getPlanarConfiguration();
int pixel = ifd.getBytesPerSample()[0];
int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel;
if (LOGGER.isTraceEnabled()) {
ifd.printIFD();
}
if (width * height > Integer.MAX_VALUE) {
throw new FormatException("Sorry, ImageWidth x ImageLength > " +
Integer.MAX_VALUE + " is not supported (" +
width + " x " + height + ")");
}
if (width * height * effectiveChannels * pixel > Integer.MAX_VALUE) {
throw new FormatException("Sorry, ImageWidth x ImageLength x " +
"SamplesPerPixel x BitsPerSample > " + Integer.MAX_VALUE +
" is not supported (" + width + " x " + height + " x " +
samplesPerPixel + " x " + (pixel * 8) + ")");
}
// casting to int is safe because we have already determined that
// width * height is less than Integer.MAX_VALUE
int numSamples = (int) (width * height);
// read in image strips
LOGGER.trace("reading image data (samplesPerPixel={}; numSamples={})",
samplesPerPixel, numSamples);
TiffCompression compression = ifd.getCompression();
if (compression == TiffCompression.JPEG_2000 ||
compression == TiffCompression.JPEG_2000_LOSSY)
{
codecOptions = compression.getCompressionCodecOptions(ifd, codecOptions);
}
else codecOptions = compression.getCompressionCodecOptions(ifd);
codecOptions.interleaved = true;
codecOptions.littleEndian = ifd.isLittleEndian();
long imageWidth = ifd.getImageWidth();
long imageLength = ifd.getImageLength();
long[] stripOffsets = null;
if (ifd.getOnDemandStripOffsets() != null) {
OnDemandLongArray offsets = ifd.getOnDemandStripOffsets();
offsets.setStream(in);
stripOffsets = offsets.toArray();
}
else {
stripOffsets = ifd.getStripOffsets();
}
if (ifd.get(IFD.STRIP_BYTE_COUNTS) instanceof OnDemandLongArray) {
OnDemandLongArray counts = (OnDemandLongArray) ifd.get(IFD.STRIP_BYTE_COUNTS);
if (counts != null) {
counts.setStream(in);
}
}
if (ifd.get(IFD.TILE_BYTE_COUNTS) instanceof OnDemandLongArray) {
OnDemandLongArray counts = (OnDemandLongArray) ifd.get(IFD.TILE_BYTE_COUNTS);
if (counts != null) {
counts.setStream(in);
}
}
long[] stripByteCounts = ifd.getStripByteCounts();
// if the image is stored as strips (not tiles) and
// the strips are stored in order with no gaps then we can
// treat them as a single strip for faster reading
boolean contiguousTiles = tileWidth == imageWidth && planarConfig == 1;
if (contiguousTiles) {
for (int i=1; i<stripOffsets.length; i++) {
if (stripOffsets[i] != stripOffsets[i - 1] + stripByteCounts[i - 1] ||
stripOffsets[i] + stripByteCounts[i] > in.length())
{
contiguousTiles = false;
break;
}
}
}
// special case: if we only need one tile, and that tile doesn't need
// any special handling, then we can just read it directly and return
if ((effectiveChannels == 1 || planarConfig == 1) && (ifd.getBitsPerSample()[0] % 8) == 0 &&
photoInterp != PhotoInterp.WHITE_IS_ZERO &&
photoInterp != PhotoInterp.CMYK && photoInterp != PhotoInterp.Y_CB_CR &&
compression == TiffCompression.UNCOMPRESSED &&
ifd.getIFDIntValue(IFD.FILL_ORDER) != 2 &&
stripOffsets != null && stripByteCounts != null &&
in.length() >= stripOffsets[0] + stripByteCounts[0] &&
(numTileRows * numTileCols == 1 || contiguousTiles))
{
if (contiguousTiles) {
stripByteCounts = new long[] {stripByteCounts[0] * stripByteCounts.length};
stripOffsets = new long[] {stripOffsets[0]};
tileLength = imageLength;
}
long column = x / tileWidth;
int firstTile = (int) ((y / tileLength) * numTileCols + column);