/
TIFFFormat.java
1565 lines (1333 loc) · 45.9 KB
/
TIFFFormat.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
* SCIFIO library for reading and converting scientific file formats.
* %%
* Copyright (C) 2011 - 2013 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package io.scif.formats;
import io.scif.AbstractFormat;
import io.scif.AbstractTranslator;
import io.scif.AbstractWriter;
import io.scif.ByteArrayPlane;
import io.scif.Format;
import io.scif.FormatException;
import io.scif.HasColorTable;
import io.scif.ImageMetadata;
import io.scif.MetadataLevel;
import io.scif.Plane;
import io.scif.Translator;
import io.scif.codec.CompressionType;
import io.scif.common.Constants;
import io.scif.common.DataTools;
import io.scif.common.DateTools;
import io.scif.formats.tiff.IFD;
import io.scif.formats.tiff.IFDList;
import io.scif.formats.tiff.PhotoInterp;
import io.scif.formats.tiff.TiffCompression;
import io.scif.formats.tiff.TiffParser;
import io.scif.formats.tiff.TiffRational;
import io.scif.formats.tiff.TiffSaver;
import io.scif.gui.AWTImageTools;
import io.scif.io.Location;
import io.scif.io.RandomAccessInputStream;
import io.scif.io.RandomAccessOutputStream;
import io.scif.util.FormatTools;
import io.scif.util.ImageTools;
import java.io.IOException;
import java.util.Hashtable;
import java.util.StringTokenizer;
import net.imglib2.display.ColorTable;
import net.imglib2.meta.Axes;
import org.scijava.plugin.Attr;
import org.scijava.plugin.Plugin;
@Plugin(type = Format.class, priority = TIFFFormat.PRIORITY)
public class TIFFFormat extends AbstractFormat {
// -- Constants --
public static final double PRIORITY = MinimalTIFFFormat.PRIORITY + 1;
public static final String[] COMPANION_SUFFIXES = { "xml", "txt" };
public static final String[] TIFF_SUFFIXES = { "tif", "tiff", "tf2", "tf8",
"btf" };
// -- Format API methods --
@Override
public String getFormatName() {
return "Tagged Image File Format";
}
@Override
public String[] getSuffixes() {
return TIFF_SUFFIXES;
}
// -- Nested classes --
/**
* @author Mark Hiner
*/
public static class Metadata extends MinimalTIFFFormat.Metadata {
// -- Fields --
private boolean populateImageMetadata = true;
// FIXME: these are duplicating metadata store information..
private String creationDate;
private String experimenterFirstName;
private String experimenterLastName;
private String experimenterEmail;
private String imageDescription;
private double physicalSizeX;
private double physicalSizeY;
private String companionFile;
private String description;
private String calibrationUnit;
private Double physicalSizeZ;
private Double timeIncrement;
private Integer xOrigin, yOrigin;
// -- Constants --
public static final String CNAME = "io.scif.formats.TIFFFormat$Metadata";
// -- TIFFMetadata getters and setters --
public String getCompanionFile() {
return companionFile;
}
public void setCompanionFile(final String companionFile) {
this.companionFile = companionFile;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getCalibrationUnit() {
return calibrationUnit;
}
public void setCalibrationUnit(final String calibrationUnit) {
this.calibrationUnit = calibrationUnit;
}
public Double getPhysicalSizeZ() {
return physicalSizeZ == null ? 1.0 : physicalSizeZ;
}
public void setPhysicalSizeZ(final Double physicalSizeZ) {
this.physicalSizeZ = physicalSizeZ;
}
public Double getTimeIncrement() {
return timeIncrement == null ? 1.0 : timeIncrement;
}
public void setTimeIncrement(final Double timeIncrement) {
this.timeIncrement = timeIncrement;
}
public Integer getxOrigin() {
return xOrigin;
}
public void setxOrigin(final Integer xOrigin) {
this.xOrigin = xOrigin;
}
public Integer getyOrigin() {
return yOrigin;
}
public void setyOrigin(final Integer yOrigin) {
this.yOrigin = yOrigin;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(final String creationDate) {
this.creationDate = creationDate;
}
public String getExperimenterFirstName() {
return experimenterFirstName;
}
public void setExperimenterFirstName(final String experimenterFirstName) {
this.experimenterFirstName = experimenterFirstName;
}
public String getExperimenterLastName() {
return experimenterLastName;
}
public void setExperimenterLastName(final String experimenterLastName) {
this.experimenterLastName = experimenterLastName;
}
public String getExperimenterEmail() {
return experimenterEmail;
}
public void setExperimenterEmail(final String experimenterEmail) {
this.experimenterEmail = experimenterEmail;
}
public String getImageDescription() {
return imageDescription;
}
public void setImageDescription(final String imageDescription) {
this.imageDescription = imageDescription;
}
public double getPhysicalSizeX() {
return physicalSizeX;
}
public void setPhysicalSizeX(final double physicalSizeX) {
this.physicalSizeX = physicalSizeX;
}
public double getPhysicalSizeY() {
return physicalSizeY;
}
public void setPhysicalSizeY(final double physicalSizeY) {
this.physicalSizeY = physicalSizeY;
}
// -- Metadata API Methods --
@Override
public void createImageMetadata(final int imageCount) {
populateImageMetadata = true;
super.createImageMetadata(imageCount);
}
@Override
public void populateImageMetadata() {
if (populateImageMetadata) super.populateImageMetadata();
final ImageMetadata m = get(0);
if (getIfds().size() > 1) m.setOrderCertain(false);
}
@Override
public void close(final boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
companionFile = null;
description = null;
calibrationUnit = null;
physicalSizeZ = null;
timeIncrement = null;
xOrigin = null;
yOrigin = null;
}
}
}
/**
* @author Mark Hiner
*/
public static class Parser extends BaseTIFFParser {
// -- Constants --
public static final int IMAGEJ_TAG = 50839;
// -- Parser API Methods --
@Override
public String[] getImageUsedFiles(final int ImageIndex,
final boolean noPixels)
{
if (noPixels) {
return metadata.getCompanionFile() == null ? null
: new String[] { metadata.getCompanionFile() };
}
if (metadata.getCompanionFile() != null) return new String[] {
metadata.getCompanionFile(), currentId };
return new String[] { currentId };
}
// -- BaseTIFFParser API Methods
@Override
protected void initStandardMetadata(final Metadata meta)
throws FormatException, IOException
{
super.initStandardMetadata(meta);
final IFDList ifds = meta.getIfds();
final String comment = ifds.get(0).getComment();
log().info("Checking comment style");
// check for reusable proprietary tags (65000-65535),
// which may contain additional metadata
final MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level != MetadataLevel.MINIMUM) {
final Integer[] tags = ifds.get(0).keySet().toArray(new Integer[0]);
for (final Integer tag : tags) {
if (tag.intValue() >= 65000) {
final Object value = ifds.get(0).get(tag);
if (value instanceof short[]) {
final short[] s = (short[]) value;
final byte[] b = new byte[s.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) s[i];
}
String metadata =
DataTools.stripString(new String(b, Constants.ENCODING));
if (metadata.indexOf("xml") != -1) {
metadata = metadata.substring(metadata.indexOf("<"));
metadata =
"<root>" + scifio().xml().sanitizeXML(metadata) + "</root>";
try {
final Hashtable<String, String> xmlMetadata =
scifio().xml().parseXML(metadata);
for (final String key : xmlMetadata.keySet()) {
addGlobalMeta(key, xmlMetadata.get(key));
}
}
catch (final IOException e) {}
}
else {
addGlobalMeta(tag.toString(), metadata);
}
}
}
}
}
// check for ImageJ-style TIFF comment
final boolean ij = checkCommentImageJ(meta, comment);
if (ij) parseCommentImageJ(meta, comment);
// check for MetaMorph-style TIFF comment
final boolean metamorph = checkCommentMetamorph(meta, comment);
if (metamorph && level != MetadataLevel.MINIMUM) {
parseCommentMetamorph(meta, comment);
}
put("MetaMorph", metamorph ? "yes" : "no");
// check for other INI-style comment
if (!ij && !metamorph && level != MetadataLevel.MINIMUM) {
parseCommentGeneric(meta, comment);
}
// check for another file with the same name
if (isGroupFiles()) {
final Location currentFile =
new Location(getContext(), currentId).getAbsoluteFile();
final String currentName = currentFile.getName();
final Location directory = currentFile.getParentFile();
final String[] files = directory.list(true);
if (files != null) {
for (final String file : files) {
String name = file;
if (name.indexOf(".") != -1) {
name = name.substring(0, name.indexOf("."));
}
if (currentName.startsWith(name) &&
FormatTools.checkSuffix(name, COMPANION_SUFFIXES))
{
meta.setCompanionFile(new Location(getContext(), directory, file)
.getAbsolutePath());
break;
}
}
}
}
// TODO : parse companion file once loci.parsers package is in place
}
@Override
protected void initMetadataStore(final Metadata meta)
throws FormatException
{
super.initMetadataStore(meta);
// MetadataStore store = makeFilterMetadata();
// if (meta.getDescription() != null) {
// store.setImageDescription(description, 0);
// }
populateMetadataStoreImageJ(meta);
}
// -- Helper methods --
private boolean
checkCommentImageJ(final Metadata meta, final String comment)
{
return comment != null && comment.startsWith("ImageJ=");
}
private boolean checkCommentMetamorph(final Metadata meta,
final String comment)
{
final String software =
meta.getIfds().get(0).getIFDTextValue(IFD.SOFTWARE);
return comment != null && software != null &&
software.indexOf("MetaMorph") != -1;
}
private void parseCommentImageJ(final Metadata meta, String comment)
throws FormatException, IOException
{
meta.populateImageMetadata();
meta.populateImageMetadata = false;
final int nl = comment.indexOf("\n");
put("ImageJ", nl < 0 ? comment.substring(7) : comment.substring(7, nl));
meta.getTable().remove("Comment");
meta.setDescription("");
int z = 1, t = 1;
int c = meta.getAxisLength(0, Axes.CHANNEL);
IFDList ifds = meta.getIfds();
if (ifds.get(0).containsKey(IMAGEJ_TAG)) {
comment += "\n" + ifds.get(0).getIFDTextValue(IMAGEJ_TAG);
}
// parse ImageJ metadata (ZCT sizes, calibration units, etc.)
final StringTokenizer st = new StringTokenizer(comment, "\n");
while (st.hasMoreTokens()) {
final String token = st.nextToken();
String value = null;
final int eq = token.indexOf("=");
if (eq >= 0) value = token.substring(eq + 1);
if (token.startsWith("channels=")) c = parseInt(value);
else if (token.startsWith("slices=")) z = parseInt(value);
else if (token.startsWith("frames=")) t = parseInt(value);
else if (token.startsWith("mode=")) {
put("Color mode", value);
}
else if (token.startsWith("unit=")) {
meta.setCalibrationUnit(value);
put("Unit", meta.getCalibrationUnit());
}
else if (token.startsWith("finterval=")) {
meta.setTimeIncrement(parseDouble(value));
put("Frame Interval", meta.getTimeIncrement());
}
else if (token.startsWith("spacing=")) {
meta.setPhysicalSizeZ(parseDouble(value));
put("Spacing", meta.getPhysicalSizeZ());
}
else if (token.startsWith("xorigin=")) {
meta.setxOrigin(parseInt(value));
put("X Origin", meta.getxOrigin());
}
else if (token.startsWith("yorigin=")) {
meta.setyOrigin(parseInt(value));
put("Y Origin", meta.getyOrigin());
}
else if (eq > 0) {
put(token.substring(0, eq).trim(), value);
}
}
if (z * c * t == c && meta.isRGB(0)) {
t = meta.getPlaneCount(0);
}
final ImageMetadata m = meta.get(0);
m.setAxisTypes(FormatTools.findDimensionList("XYCZT"));
if (z * t * (m.isRGB() ? 1 : c) == ifds.size()) {
m.setAxisLength(Axes.Z, z);
m.setAxisLength(Axes.TIME, t);
m.setAxisLength(Axes.CHANNEL, m.isRGB() ? m.getAxisLength(Axes.CHANNEL)
: c);
}
else if (z * c * t == ifds.size() && m.isRGB()) {
m.setAxisLength(Axes.Z, z);
m.setAxisLength(Axes.TIME, t);
m.setAxisLength(Axes.CHANNEL, m.getAxisLength(Axes.CHANNEL) * c);
}
else if (ifds.size() == 1 && z * t > ifds.size() &&
ifds.get(0).getCompression() == TiffCompression.UNCOMPRESSED)
{
// file is likely corrupt (missing end IFDs)
//
// ImageJ writes TIFF files like this:
// IFD #0
// comment
// all pixel data
// IFD #1
// IFD #2
// ...
//
// since we know where the pixel data is, we can create fake
// IFDs in an attempt to read the rest of the pixels
final IFD firstIFD = ifds.get(0);
final int planeSize =
m.getAxisLength(Axes.X) * m.getAxisLength(Axes.Y) *
m.getRGBChannelCount() *
FormatTools.getBytesPerPixel(m.getPixelType());
final long[] stripOffsets = firstIFD.getStripOffsets();
final long[] stripByteCounts = firstIFD.getStripByteCounts();
final long endOfFirstPlane =
stripOffsets[stripOffsets.length - 1] +
stripByteCounts[stripByteCounts.length - 1];
final long totalBytes = in.length() - endOfFirstPlane;
final int totalPlanes = (int) (totalBytes / planeSize) + 1;
ifds = new IFDList();
ifds.add(firstIFD);
for (int i = 1; i < totalPlanes; i++) {
final IFD ifd = new IFD(firstIFD, log());
ifds.add(ifd);
final long[] prevOffsets = ifds.get(i - 1).getStripOffsets();
final long[] offsets = new long[stripOffsets.length];
offsets[0] =
prevOffsets[prevOffsets.length - 1] +
stripByteCounts[stripByteCounts.length - 1];
for (int j = 1; j < offsets.length; j++) {
offsets[j] = offsets[j - 1] + stripByteCounts[j - 1];
}
ifd.putIFDValue(IFD.STRIP_OFFSETS, offsets);
}
if (z * c * t == ifds.size()) {
m.setAxisLength(Axes.Z, z);
m.setAxisLength(Axes.TIME, t);
m.setAxisLength(Axes.CHANNEL, c);
}
else if (z * t == ifds.size()) {
m.setAxisLength(Axes.Z, z);
m.setAxisLength(Axes.TIME, t);
}
else m.setAxisLength(Axes.Z, ifds.size());
m.setPlaneCount(ifds.size());
}
else {
m.setAxisLength(Axes.TIME, ifds.size());
m.setPlaneCount(ifds.size());
}
}
/**
* Checks the original metadata table for ImageJ-specific information to
* propagate into the metadata store.
*/
private void populateMetadataStoreImageJ(final Metadata meta) {
// TODO: Perhaps we should only populate the physical Z size if the unit
// is
// a known, physical quantity such as "micron" rather than "pixel".
// e.g.: if (calibrationUnit.equals("micron"))
if (meta.getPhysicalSizeZ() != null) {
double zDepth = meta.getPhysicalSizeZ();
if (zDepth < 0) zDepth = -zDepth;
if (zDepth > 0) {
meta.setPhysicalSizeZ(zDepth);
}
else {
log()
.warn("Expected positive value for PhysicalSizeZ; got " + zDepth);
}
}
}
private void
parseCommentMetamorph(final Metadata meta, final String comment)
{
// parse key/value pairs
final StringTokenizer st = new StringTokenizer(comment, "\n");
while (st.hasMoreTokens()) {
final String line = st.nextToken();
final int colon = line.indexOf(":");
if (colon < 0) {
addGlobalMeta("Comment", line);
meta.setDescription(line);
continue;
}
final String key = line.substring(0, colon);
final String value = line.substring(colon + 1);
addGlobalMeta(key, value);
}
}
private void parseCommentGeneric(final Metadata meta, String comment) {
if (comment == null) return;
final String[] lines = comment.split("\n");
if (lines.length > 1) {
comment = "";
for (final String line : lines) {
final int eq = line.indexOf("=");
if (eq != -1) {
final String key = line.substring(0, eq).trim();
final String value = line.substring(eq + 1).trim();
addGlobalMeta(key, value);
}
else if (!line.startsWith("[")) {
comment += line + "\n";
}
}
addGlobalMeta("Comment", comment);
meta.setDescription(comment);
}
}
private int parseInt(final String s) {
try {
return Integer.parseInt(s);
}
catch (final NumberFormatException e) {
log().debug("Failed to parse integer value", e);
}
return 0;
}
private double parseDouble(final String s) {
try {
return Double.parseDouble(s);
}
catch (final NumberFormatException e) {
log().debug("Failed to parse floating point value", e);
}
return 0;
}
}
/**
* BaseTiffReader is the superclass for file format readers compatible with or
* derived from the TIFF 6.0 file format.
*
* @author Curtis Rueden
* @author Melissa Linkert
*/
public static abstract class BaseTIFFParser extends
MinimalTIFFFormat.Parser<Metadata>
{
// -- Constants --
public static final String[] DATE_FORMATS = { "yyyy:MM:dd HH:mm:ss",
"dd/MM/yyyy HH:mm:ss.SS", "MM/dd/yyyy hh:mm:ss.SSS aa",
"yyyyMMdd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss" };
// -- Parser API Methods --
@Override
protected void typedParse(final RandomAccessInputStream stream,
final Metadata meta) throws IOException, FormatException
{
super.typedParse(stream, meta);
initMetadata(meta);
}
// -- Internal BaseTiffReader API methods --
/** Populates the metadata hashtable and metadata store. */
protected void initMetadata(final Metadata meta) throws FormatException,
IOException
{
initStandardMetadata(meta);
initMetadataStore(meta);
}
/**
* Parses standard metadata. NOTE: Absolutely <b>no</b> calls to the
* metadata store should be made in this method or methods that override
* this method. Data <b>will</b> be overwritten if you do so.
*/
protected void initStandardMetadata(final Metadata meta)
throws FormatException, IOException
{
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
return;
}
final IFDList ifds = meta.getIfds();
for (int i = 0; i < ifds.size(); i++) {
put("PageName #" + i, ifds.get(i), IFD.PAGE_NAME);
}
final IFD firstIFD = ifds.get(0);
put("ImageWidth", firstIFD, IFD.IMAGE_WIDTH);
put("ImageLength", firstIFD, IFD.IMAGE_LENGTH);
put("BitsPerSample", firstIFD, IFD.BITS_PER_SAMPLE);
// retrieve EXIF values, if available
if (ifds.get(0).containsKey(IFD.EXIF)) {
final IFDList exifIFDs = meta.getTiffParser().getExifIFDs();
if (exifIFDs.size() > 0) {
final IFD exif = exifIFDs.get(0);
for (final Integer key : exif.keySet()) {
final int k = key.intValue();
addGlobalMeta(getExifTagName(k), exif.get(key));
}
}
}
final TiffCompression comp = firstIFD.getCompression();
put("Compression", comp.getCodecName());
final PhotoInterp photo = firstIFD.getPhotometricInterpretation();
final String photoInterp = photo.getName();
final String metaDataPhotoInterp = photo.getMetadataType();
put("PhotometricInterpretation", photoInterp);
put("MetaDataPhotometricInterpretation", metaDataPhotoInterp);
putInt("CellWidth", firstIFD, IFD.CELL_WIDTH);
putInt("CellLength", firstIFD, IFD.CELL_LENGTH);
final int or = firstIFD.getIFDIntValue(IFD.ORIENTATION);
// adjust the width and height if necessary
if (or == 8) {
put("ImageWidth", firstIFD, IFD.IMAGE_LENGTH);
put("ImageLength", firstIFD, IFD.IMAGE_WIDTH);
}
String orientation = null;
// there is no case 0
switch (or) {
case 1:
orientation = "1st row -> top; 1st column -> left";
break;
case 2:
orientation = "1st row -> top; 1st column -> right";
break;
case 3:
orientation = "1st row -> bottom; 1st column -> right";
break;
case 4:
orientation = "1st row -> bottom; 1st column -> left";
break;
case 5:
orientation = "1st row -> left; 1st column -> top";
break;
case 6:
orientation = "1st row -> right; 1st column -> top";
break;
case 7:
orientation = "1st row -> right; 1st column -> bottom";
break;
case 8:
orientation = "1st row -> left; 1st column -> bottom";
break;
}
put("Orientation", orientation);
putInt("SamplesPerPixel", firstIFD, IFD.SAMPLES_PER_PIXEL);
put("Software", firstIFD, IFD.SOFTWARE);
put("Instrument Make", firstIFD, IFD.MAKE);
put("Instrument Model", firstIFD, IFD.MODEL);
put("Document Name", firstIFD, IFD.DOCUMENT_NAME);
put("DateTime", firstIFD, IFD.DATE_TIME);
put("Artist", firstIFD, IFD.ARTIST);
put("HostComputer", firstIFD, IFD.HOST_COMPUTER);
put("Copyright", firstIFD, IFD.COPYRIGHT);
put("NewSubfileType", firstIFD, IFD.NEW_SUBFILE_TYPE);
final int thresh = firstIFD.getIFDIntValue(IFD.THRESHHOLDING);
String threshholding = null;
switch (thresh) {
case 1:
threshholding = "No dithering or halftoning";
break;
case 2:
threshholding = "Ordered dithering or halftoning";
break;
case 3:
threshholding = "Randomized error diffusion";
break;
}
put("Threshholding", threshholding);
final int fill = firstIFD.getIFDIntValue(IFD.FILL_ORDER);
String fillOrder = null;
switch (fill) {
case 1:
fillOrder =
"Pixels with lower column values are stored "
+ "in the higher order bits of a byte";
break;
case 2:
fillOrder =
"Pixels with lower column values are stored "
+ "in the lower order bits of a byte";
break;
}
put("FillOrder", fillOrder);
putInt("Make", firstIFD, IFD.MAKE);
putInt("Model", firstIFD, IFD.MODEL);
putInt("MinSampleValue", firstIFD, IFD.MIN_SAMPLE_VALUE);
putInt("MaxSampleValue", firstIFD, IFD.MAX_SAMPLE_VALUE);
putInt("XResolution", firstIFD, IFD.X_RESOLUTION);
putInt("YResolution", firstIFD, IFD.Y_RESOLUTION);
final int planar = firstIFD.getIFDIntValue(IFD.PLANAR_CONFIGURATION);
String planarConfig = null;
switch (planar) {
case 1:
planarConfig = "Chunky";
break;
case 2:
planarConfig = "Planar";
break;
}
put("PlanarConfiguration", planarConfig);
putInt("XPosition", firstIFD, IFD.X_POSITION);
putInt("YPosition", firstIFD, IFD.Y_POSITION);
putInt("FreeOffsets", firstIFD, IFD.FREE_OFFSETS);
putInt("FreeByteCounts", firstIFD, IFD.FREE_BYTE_COUNTS);
putInt("GrayResponseUnit", firstIFD, IFD.GRAY_RESPONSE_UNIT);
putInt("GrayResponseCurve", firstIFD, IFD.GRAY_RESPONSE_CURVE);
putInt("T4Options", firstIFD, IFD.T4_OPTIONS);
putInt("T6Options", firstIFD, IFD.T6_OPTIONS);
final int res = firstIFD.getIFDIntValue(IFD.RESOLUTION_UNIT);
String resUnit = null;
switch (res) {
case 1:
resUnit = "None";
break;
case 2:
resUnit = "Inch";
break;
case 3:
resUnit = "Centimeter";
break;
}
put("ResolutionUnit", resUnit);
putInt("PageNumber", firstIFD, IFD.PAGE_NUMBER);
putInt("TransferFunction", firstIFD, IFD.TRANSFER_FUNCTION);
final int predict = firstIFD.getIFDIntValue(IFD.PREDICTOR);
String predictor = null;
switch (predict) {
case 1:
predictor = "No prediction scheme";
break;
case 2:
predictor = "Horizontal differencing";
break;
}
put("Predictor", predictor);
putInt("WhitePoint", firstIFD, IFD.WHITE_POINT);
putInt("PrimaryChromacities", firstIFD, IFD.PRIMARY_CHROMATICITIES);
putInt("HalftoneHints", firstIFD, IFD.HALFTONE_HINTS);
putInt("TileWidth", firstIFD, IFD.TILE_WIDTH);
putInt("TileLength", firstIFD, IFD.TILE_LENGTH);
putInt("TileOffsets", firstIFD, IFD.TILE_OFFSETS);
putInt("TileByteCounts", firstIFD, IFD.TILE_BYTE_COUNTS);
final int ink = firstIFD.getIFDIntValue(IFD.INK_SET);
String inkSet = null;
switch (ink) {
case 1:
inkSet = "CMYK";
break;
case 2:
inkSet = "Other";
break;
}
put("InkSet", inkSet);
putInt("InkNames", firstIFD, IFD.INK_NAMES);
putInt("NumberOfInks", firstIFD, IFD.NUMBER_OF_INKS);
putInt("DotRange", firstIFD, IFD.DOT_RANGE);
put("TargetPrinter", firstIFD, IFD.TARGET_PRINTER);
putInt("ExtraSamples", firstIFD, IFD.EXTRA_SAMPLES);
final int fmt = firstIFD.getIFDIntValue(IFD.SAMPLE_FORMAT);
String sampleFormat = null;
switch (fmt) {
case 1:
sampleFormat = "unsigned integer";
break;
case 2:
sampleFormat = "two's complement signed integer";
break;
case 3:
sampleFormat = "IEEE floating point";
break;
case 4:
sampleFormat = "undefined";
break;
}
put("SampleFormat", sampleFormat);
putInt("SMinSampleValue", firstIFD, IFD.S_MIN_SAMPLE_VALUE);
putInt("SMaxSampleValue", firstIFD, IFD.S_MAX_SAMPLE_VALUE);
putInt("TransferRange", firstIFD, IFD.TRANSFER_RANGE);
final int jpeg = firstIFD.getIFDIntValue(IFD.JPEG_PROC);
String jpegProc = null;
switch (jpeg) {
case 1:
jpegProc = "baseline sequential process";
break;
case 14:
jpegProc = "lossless process with Huffman coding";
break;
}
put("JPEGProc", jpegProc);
putInt("JPEGInterchangeFormat", firstIFD, IFD.JPEG_INTERCHANGE_FORMAT);
putInt("JPEGRestartInterval", firstIFD, IFD.JPEG_RESTART_INTERVAL);
putInt("JPEGLosslessPredictors", firstIFD, IFD.JPEG_LOSSLESS_PREDICTORS);
putInt("JPEGPointTransforms", firstIFD, IFD.JPEG_POINT_TRANSFORMS);
putInt("JPEGQTables", firstIFD, IFD.JPEG_Q_TABLES);
putInt("JPEGDCTables", firstIFD, IFD.JPEG_DC_TABLES);
putInt("JPEGACTables", firstIFD, IFD.JPEG_AC_TABLES);
putInt("YCbCrCoefficients", firstIFD, IFD.Y_CB_CR_COEFFICIENTS);
final int ycbcr = firstIFD.getIFDIntValue(IFD.Y_CB_CR_SUB_SAMPLING);
String subSampling = null;
switch (ycbcr) {
case 1:
subSampling = "chroma image dimensions = luma image dimensions";
break;
case 2:
subSampling =
"chroma image dimensions are " + "half the luma image dimensions";
break;
case 4:
subSampling =
"chroma image dimensions are " + "1/4 the luma image dimensions";
break;
}
put("YCbCrSubSampling", subSampling);
putInt("YCbCrPositioning", firstIFD, IFD.Y_CB_CR_POSITIONING);
putInt("ReferenceBlackWhite", firstIFD, IFD.REFERENCE_BLACK_WHITE);
// bits per sample and number of channels
final int[] q = firstIFD.getBitsPerSample();
final int bps = q[0];
int numC = q.length;
// numC isn't set properly if we have an indexed color image, so we need
// to reset it here
if (photo == PhotoInterp.RGB_PALETTE || photo == PhotoInterp.CFA_ARRAY) {
numC = 3;
}
put("BitsPerSample", bps);
put("NumberOfChannels", numC);
}
/**
* Populates the metadata store using the data parsed in
* {@link #initStandardMetadata()} along with some further parsing done in
* the method itself. All calls to the active <code>MetadataStore</code>
* should be made in this method and <b>only</b> in this method. This is
* especially important for sub-classes that override the getters for pixel
* set array size, etc.
*/
protected void initMetadataStore(final Metadata meta)
throws FormatException
{
log().info("Populating OME metadata");
final IFD firstIFD = meta.getIfds().get(0);
// format the creation date to ISO 8601