/
TIFFTweaker.java
3694 lines (3269 loc) · 143 KB
/
TIFFTweaker.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) 2014-2019 WEN YU (YUWEN_66@YAHOO.COM) ALL RIGHTS RESERVED.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Any modifications to this file must keep this entire header intact.
*
* Change History - most recent changes go on top of previous changes
*
* TIFFTweaker.java
*
* Who Date Description
* ==== ========= ===================================================================
* WY 21Jun2019 Added code for removeMetadata to return the removed metadata as a map
* WY 04May2019 Write IPTC to normal TIFF IPTC tag instead of PhotoShop IRB block
* WY 09Aug2018 Add prepareForWrite(RandomAccessOutputStream, ByteOrder)
* WY 09Aug2018 Add ByteOrder support to writeMultipageTIFF
* WY 06Apr2018 Added extractThumbnails(RandomAccessInputStream)
* WY 14Dec2017 Replace some of the RuntimeException with customized exception
* WY 13Dec2017 Replace e.printStackTrace() with logging and/or RuntimeException
* WY 20Nov2017 Added re-factored merge() method
* WY 09Sep2017 Added split a multiple page TIFF into smaller multiple page TIFF
* SV 05Sep2017 Added split a multiple page TIFF into single page TIFFs byte arrays
* WY 04Mar2017 Added insertMetadata() to insert multiple Metadata at one time
* WY 11Dec2016 Added byte order to writeMultipageTIFF
* WY 19Aug2015 Added code to write multipage TIFF page by page
* WY 06Jul2015 Added insertXMP(InputSream, OutputStream, XMP)
* WY 21Jun2015 Removed copyright notice from generated TIFF images
* WY 15Apr2015 Changed the argument type for insertIPTC() and insertIRB()
* WY 07Apr2015 Merge Adobe IPTC and TIFF IPTC if both exist
* WY 15Mar2015 Cleanup debugging output
* WY 18Feb2015 Added removeMetadata() to remove meta data from TIFF
* WY 14Feb2015 Added insertXMP() to insert XMP data to TIFF
* WY 06Feb2015 Added printIFDs() and printIFD()
* WY 04Feb2015 Revised insertExif() to keep original EXIF data is needed
* WY 03Feb2015 Added removeExif() to remove EXIF and GPS data from TIFF image
* WY 01Feb2015 Revised to remove duplicates when combining normal and Photoshop IPTC
* WY 29Jan2015 Revised insertIPTC() and insertIRB() to keep old data
* WY 27Jan2015 Implemented insertThumbnail() to insert thumbnail to Photoshop IRB
* WY 27Jan2015 Added insertIRB() to insert Photoshop IRB data
* WY 26Jan2015 Added insertIPTC() to insert IPTC data
* WY 20Jan2015 Revised to work with Metadata.showMetadata()
* WY 12Jan2015 Added showIPTC() to show IPTC private tag information
* WY 11Jan2015 Added extractThumbnail() to extract Photoshop thumbnail
* WY 10Jan2015 Added showICCProfile() and showPhotoshop()
* WY 23Dec2014 Added extractICCProfile() to extract ICC_Profile from TIFF image
* WY 22Dec2014 Added insertICCProfile() to insert ICC_Profile into TIFF image
* WY 17Dec2014 Changed TIFFFrame to ImageFrame due to rename of TIFFFrame
* WY 15Dec2014 Added insertTiffImage() to insert one TIFF image into another
* WY 15Dec2014 Added append() to append new pages to the end of existing TIFF
* WY 24Nov2014 Changed removePages() to remove the actual pages from the arguments
* WY 24Nov2014 Changed write(TIFFImage) to write(TIFFImage, RandomAccessOutputStream)
* WY 22Nov2014 Removed unnecessary TIFFWriter argument from corresponding methods
* WY 21Nov2014 Added new writeMultipageTIFF() to use TIFFFrame array as argument
* WY 12Nov2014 Added support for up to 32 BitsPerSample image to mergeTiffImagesEx()
* WY 11Nov2014 Added getRowWidth() to determine scan line stride
* WY 07Nov2014 Fixed bug for mergeTiffImagesEx() when there is no compression field
* WY 06Nov2014 Fixed bug for getUncompressedStripByteCounts() with YCbCr image
* WY 28Oct2014 Changed mergeTiffImagesEx() to use flipEndian() from ArrayUtils
* WY 24Oct2014 Added getBytes2Read() to fix bug of uncompressed image with only one
* strip/SamplesPerPixel strips for PlanaryConfiguration = 2 and wrong
* StripByteCounts value/values
* WY 24Oct2014 Revised getUncompressedStripByteCounts to include YCbCrSubSampling
* WY 21Oct2014 Changed copyPageData() and mergeTiffImagesEx() to use the extracted
* getUncompressedStripByteCounts() method
* WY 21Oct2014 Extracted method getUncompressedStripByteCounts()
* WY 20Oct2014 Added mergeTiffImagesEx(RandomAccessOutputStream, File...)
* WY 09Oct2014 Added mergeTiffImages(RandomAccessOutputStream, File...)
* WY 07Oct2014 Added mergeTiffImages() to merge two multiple page TIFFs
* WY 19Sep2014 Reset pointer to the stream head in getPageCount()
* WY 08May2014 Added insertExif() to insert EXIF data to TIFF page
* WY 26Apr2014 Rewrite insertPage() to insert multiple pages one at a time
* WY 11Apr2014 Added writeMultipageTIFF() to support creating multiple page TIFFs
* WY 09Apr2014 Added splitPages() to split multiple page TIFFs into single page TIFFs
* WY 09Apr2014 Added insertPages() to insert pages to multiple page TIFFs
* WY 08Apr2014 Added insertPage() to insert a single page to multiple page TIFFs
* WY 07Apr2014 Added getPageCount() to get the total pages for a TIFF image
* WY 06Apr2014 Added retainPages() to keep pages from multiple page TIFFs
* WY 04Apr2014 Added removePages() to remove pages from multiple page TIFFs
* WY 02Apr2014 Added writePageData() for multiple page TIFFs
*/
package com.icafe4j.image.tiff;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.icafe4j.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import com.icafe4j.image.ImageFrame;
import com.icafe4j.image.ImageIO;
import com.icafe4j.image.ImageParam;
import com.icafe4j.image.ImageType;
import com.icafe4j.image.compression.CodecException;
import com.icafe4j.image.compression.ImageDecoder;
import com.icafe4j.image.compression.ImageEncoder;
import com.icafe4j.image.compression.deflate.DeflateDecoder;
import com.icafe4j.image.compression.deflate.DeflateEncoder;
import com.icafe4j.image.compression.lzw.LZWTreeDecoder;
import com.icafe4j.image.compression.lzw.LZWTreeEncoder;
import com.icafe4j.image.compression.packbits.Packbits;
import com.icafe4j.image.jpeg.Marker;
import com.icafe4j.image.meta.Metadata;
import com.icafe4j.image.meta.MetadataType;
import com.icafe4j.image.meta.Thumbnail;
import com.icafe4j.image.meta.adobe.DDB;
import com.icafe4j.image.meta.adobe.IRB;
import com.icafe4j.image.meta.adobe.IRBThumbnail;
import com.icafe4j.image.meta.adobe.ImageResourceID;
import com.icafe4j.image.meta.adobe.ThumbnailResource;
import com.icafe4j.image.meta.adobe._8BIM;
import com.icafe4j.image.meta.exif.Exif;
import com.icafe4j.image.meta.exif.ExifTag;
import com.icafe4j.image.meta.exif.GPSTag;
import com.icafe4j.image.meta.exif.InteropTag;
import com.icafe4j.image.meta.icc.ICCProfile;
import com.icafe4j.image.meta.image.Comments;
import com.icafe4j.image.meta.image.ImageMetadata;
import com.icafe4j.image.meta.iptc.IPTC;
import com.icafe4j.image.meta.iptc.IPTCDataSet;
import com.icafe4j.image.meta.iptc.IPTCTag;
import com.icafe4j.image.meta.tiff.TiffExif;
import com.icafe4j.image.meta.tiff.TiffXMP;
import com.icafe4j.image.meta.xmp.XMP;
import com.icafe4j.image.options.TIFFOptions;
import com.icafe4j.image.tiff.TiffFieldEnum.PhotoMetric;
import com.icafe4j.image.writer.ImageWriter;
import com.icafe4j.image.writer.TIFFWriter;
import com.icafe4j.string.StringUtils;
import com.icafe4j.string.XMLUtils;
import com.icafe4j.util.ArrayUtils;
import static com.icafe4j.image.writer.TIFFWriter.*;
/**
* TIFF image tweaking tool
*
* @author Wen Yu, yuwen_66@yahoo.com
* @version 1.0 03/28/2014
*/
public class TIFFTweaker {
// Obtain a logger instance
private static final Logger LOGGER = LoggerFactory.getLogger(TIFFTweaker.class);
public static void append(RandomAccessInputStream rin, RandomAccessOutputStream rout, BufferedImage ... images) throws IOException {
append(rin, rout, null, images);
}
/**
* Append ImageFrames to the end of the original TIFF image
*
* @param frames an array of ImageFrame to be appended
* @param rin RandomAccessInputStream for the input image
* @param rout RandomAccessOutputStream for the output image
* @throws IOException
*/
public static void append(RandomAccessInputStream rin, RandomAccessOutputStream rout, ImageFrame ... frames) throws IOException {
insertPages(rin, rout, getPageCount(rin), frames);
}
//
// Append an array of BufferedImage to the end of the existing TIFF image
public static void append(RandomAccessInputStream rin, RandomAccessOutputStream rout, ImageParam[] imageParam, BufferedImage ... images) throws IOException {
insertPages(rin, rout, getPageCount(rin), imageParam, images);
}
/**
* Read an input TIFF and write it to a new TIFF.
* The EXIF and GPS information, if present, are preserved.
*
* @param rin a RandomAccessInputStream
* @param rout a RandomAccessOutputStream
* @throws IOException
*/
public static void copyCat(RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
List<IFD> list = new ArrayList<IFD>();
int offset = copyHeader(rin, rout);
int writeOffset = FIRST_WRITE_OFFSET;
// Read the IFDs into a list first
readIFDs(list, offset, rin);
offset = copyPages(list, writeOffset, rin, rout);
int firstIFDOffset = list.get(0).getStartOffset();
writeToStream(rout, firstIFDOffset);
}
private static int copyHeader(RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
rin.seek(STREAM_HEAD);
// First 2 bytes determine the byte order of the file, "MM" or "II"
short endian = rin.readShort();
if (endian == IOUtils.BIG_ENDIAN) {
rin.setReadStrategy(ReadStrategyMM.getInstance());
rout.setWriteStrategy(WriteStrategyMM.getInstance());
} else if(endian == IOUtils.LITTLE_ENDIAN) {
rin.setReadStrategy(ReadStrategyII.getInstance());
rout.setWriteStrategy(WriteStrategyII.getInstance());
} else {
rin.close();
rout.close();
throw new RuntimeException("Invalid TIFF byte order");
}
rout.writeShort(endian);
// Read TIFF identifier
rin.seek(0x02);
short tiff_id = rin.readShort();
if(tiff_id != 0x2a) { //"*" 42 decimal
rin.close();
rout.close();
throw new RuntimeException("Invalid TIFF identifier");
}
rout.writeShort(tiff_id);
rin.seek(OFFSET_TO_WRITE_FIRST_IFD_OFFSET);
return rin.readInt();
}
private static Collection<IPTCDataSet> copyIPTCDataSet(Collection<IPTCDataSet> iptcs, byte[] data) throws IOException {
IPTC iptc = new IPTC(data);
// Shallow copy the map
Map<IPTCTag, List<IPTCDataSet>> dataSetMap = new HashMap<IPTCTag, List<IPTCDataSet>>(iptc.getDataSets());
for(IPTCDataSet set : iptcs)
if(!set.allowMultiple())
dataSetMap.remove(set.getTagEnum());
for(List<IPTCDataSet> iptcList : dataSetMap.values())
iptcs.addAll(iptcList);
return iptcs;
}
private static TiffField<?> copyJpegHufTable(RandomAccessInputStream rin, RandomAccessOutputStream rout, TiffField<?> field, int curPos) throws IOException {
int[] data = field.getDataAsLong();
int[] tmp = new int[data.length];
for(int i = 0; i < data.length; i++) {
rin.seek(data[i]);
tmp[i] = curPos;
byte[] htable = new byte[16];
IOUtils.readFully(rin, htable);
IOUtils.write(rout, htable);
curPos += 16;
int numCodes = 0;
for(int j = 0; j < 16; j++) {
numCodes += htable[j]&0xff;
}
curPos += numCodes;
htable = new byte[numCodes];
IOUtils.readFully(rin, htable);
IOUtils.write(rout, htable);
}
if(TiffTag.fromShort(field.getTag()) == TiffTag.JPEG_AC_TABLES)
return new LongField(TiffTag.JPEG_AC_TABLES.getValue(), tmp);
return new LongField(TiffTag.JPEG_DC_TABLES.getValue(), tmp);
}
private static void copyJpegIFByteCount(RandomAccessInputStream rin, RandomAccessOutputStream rout, int offset, int outOffset) throws IOException {
boolean finished = false;
int length = 0;
short marker;
Marker emarker;
rin.seek(offset);
rout.seek(outOffset);
// The very first marker should be the start_of_image marker!
if(Marker.fromShort(IOUtils.readShortMM(rin)) != Marker.SOI) {
return;
}
IOUtils.writeShortMM(rout, Marker.SOI.getValue());
marker = IOUtils.readShortMM(rin);
while (!finished) {
if (Marker.fromShort(marker) == Marker.EOI) {
IOUtils.writeShortMM(rout, marker);
finished = true;
} else { // Read markers
emarker = Marker.fromShort(marker);
switch (emarker) {
case JPG: // JPG and JPGn shouldn't appear in the image.
case JPG0:
case JPG13:
case TEM: // The only stand alone mark besides SOI, EOI, and RSTn.
marker = IOUtils.readShortMM(rin);
break;
case SOS:
marker = copyJpegSOS(rin, rout);
break;
case PADDING:
int nextByte = 0;
while((nextByte = rin.read()) == 0xff) {;}
marker = (short)((0xff<<8)|nextByte);
break;
default:
length = IOUtils.readUnsignedShortMM(rin);
byte[] buf = new byte[length - 2];
rin.read(buf);
IOUtils.writeShortMM(rout, marker);
IOUtils.writeShortMM(rout, length);
rout.write(buf);
marker = IOUtils.readShortMM(rin);
}
}
}
}
private static TiffField<?> copyJpegQTable(RandomAccessInputStream rin, RandomAccessOutputStream rout, TiffField<?> field, int curPos) throws IOException {
byte[] qtable = new byte[64];
int[] data = field.getDataAsLong();
int[] tmp = new int[data.length];
for(int i = 0; i < data.length; i++) {
rin.seek(data[i]);
tmp[i] = curPos;
IOUtils.readFully(rin, qtable);
IOUtils.write(rout, qtable);
curPos += 64;
}
return new LongField(TiffTag.JPEG_Q_TABLES.getValue(), tmp);
}
private static short copyJpegSOS(RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
int len = IOUtils.readUnsignedShortMM(rin);
byte buf[] = new byte[len - 2];
IOUtils.readFully(rin, buf);
IOUtils.writeShortMM(rout, Marker.SOS.getValue());
IOUtils.writeShortMM(rout, len);
rout.write(buf);
// Actual image data follow.
int nextByte = 0;
short marker = 0;
while((nextByte = IOUtils.read(rin)) != -1) {
rout.write(nextByte);
if(nextByte == 0xff)
{
nextByte = IOUtils.read(rin);
rout.write(nextByte);
if (nextByte == -1) {
throw new IOException("Premature end of SOS segment!");
}
if (nextByte != 0x00) {
marker = (short)((0xff<<8)|nextByte);
switch (Marker.fromShort(marker)) {
case RST0:
case RST1:
case RST2:
case RST3:
case RST4:
case RST5:
case RST6:
case RST7:
continue;
default:
}
break;
}
}
}
if (nextByte == -1) {
throw new IOException("Premature end of SOS segment!");
}
return marker;
}
/**
* @param offset offset to write page image data
*
* @return the position where to write the IFD for the current image page
*/
private static int copyPageData(IFD ifd, int offset, RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
int writeOffset = offset; // We copy the offset to a local variable to keep the original value
int writeByteCount = 0; // To fix JPEG data double copy issue
// Move stream pointer to the right place
rout.seek(writeOffset);
// Original image data start from these offsets.
TiffField<?> stripOffSets = ifd.removeField(TiffTag.STRIP_OFFSETS);
if(stripOffSets == null)
stripOffSets = ifd.removeField(TiffTag.TILE_OFFSETS);
TiffField<?> stripByteCounts = ifd.getField(TiffTag.STRIP_BYTE_COUNTS);
if(stripByteCounts == null)
stripByteCounts = ifd.getField(TiffTag.TILE_BYTE_COUNTS);
/*
* Make sure this will work in the case when neither STRIP_OFFSETS nor TILE_OFFSETS presents.
* Not sure if this will ever happen for TIFF. JPEG EXIF data do not contain these fields.
*/
if(stripOffSets != null) {
int[] counts = stripByteCounts.getDataAsLong();
int[] off = stripOffSets.getDataAsLong();
int[] temp = new int[off.length];
TiffField<?> tiffField = ifd.getField(TiffTag.COMPRESSION);
// Uncompressed image with one strip or tile (may contain wrong StripByteCounts value)
// Bug fix for uncompressed image with one strip and wrong StripByteCounts value
if((tiffField == null ) || (tiffField != null && tiffField.getDataAsLong()[0] == 1)) { // Uncompressed data
int planaryConfiguration = 1;
tiffField = ifd.getField(TiffTag.PLANAR_CONFIGURATTION);
if(tiffField != null) planaryConfiguration = tiffField.getDataAsLong()[0];
tiffField = ifd.getField(TiffTag.SAMPLES_PER_PIXEL);
int samplesPerPixel = 1;
if(tiffField != null) samplesPerPixel = tiffField.getDataAsLong()[0];
// If there is only one strip/samplesPerPixel strips for PlanaryConfiguration = 2
if((planaryConfiguration == 1 && off.length == 1) || (planaryConfiguration == 2 && off.length == samplesPerPixel)) {
int[] totalBytes2Read = getBytes2Read(ifd);
for(int i = 0; i < off.length; i++)
counts[i] = totalBytes2Read[i];
}
} // End of bug fix
writeByteCount = counts[0];
// We are going to write the image data first
rout.seek(writeOffset);
// Copy image data from offset
for(int i = 0; i < off.length; i++) {
rin.seek(off[i]);
byte[] buf = new byte[counts[i]];
rin.readFully(buf);
rout.write(buf);
temp[i] = writeOffset;
writeOffset += buf.length;
}
if(ifd.getField(TiffTag.STRIP_BYTE_COUNTS) != null)
ifd.addField(new LongField(TiffTag.STRIP_OFFSETS.getValue(), temp));
else
ifd.addField(new LongField(TiffTag.TILE_OFFSETS.getValue(), temp));
}
// Add software field.
String softWare = "ICAFE - https://github.com/dragon66/icafe\0";
ifd.addField(new ASCIIField(TiffTag.SOFTWARE.getValue(), softWare));
/* The following are added to work with old-style JPEG compression (type 6) */
/* One of the flavors (found in JPEG EXIF thumbnail IFD - IFD1) of the old JPEG compression contains this field */
TiffField<?> jpegIFOffset = ifd.removeField(TiffTag.JPEG_INTERCHANGE_FORMAT);
if(jpegIFOffset != null) {
TiffField<?> jpegIFByteCount = ifd.removeField(TiffTag.JPEG_INTERCHANGE_FORMAT_LENGTH);
if(jpegIFOffset.getDataAsLong()[0] != stripOffSets.getDataAsLong()[0]) {
try {
if(jpegIFByteCount != null) {
rin.seek(jpegIFOffset.getDataAsLong()[0]);
byte[] bytes2Read = new byte[jpegIFByteCount.getDataAsLong()[0]];
rin.readFully(bytes2Read);
rout.seek(writeOffset);
rout.write(bytes2Read);
ifd.addField(jpegIFByteCount);
} else {
long startOffset = rout.getStreamPointer();
copyJpegIFByteCount(rin, rout, jpegIFOffset.getDataAsLong()[0], writeOffset);
long endOffset = rout.getStreamPointer();
ifd.addField(new LongField(TiffTag.JPEG_INTERCHANGE_FORMAT_LENGTH.getValue(), new int[]{(int)(endOffset - startOffset)}));
}
jpegIFOffset = new LongField(TiffTag.JPEG_INTERCHANGE_FORMAT.getValue(), new int[]{writeOffset});
ifd.addField(jpegIFOffset);
} catch (EOFException ex) {;};
} else { // To fix the issue of double copy the JPEG data, we can safely re-assign the pointers.
ifd.addField(new LongField(TiffTag.JPEG_INTERCHANGE_FORMAT.getValue(), new int[]{offset}));
ifd.addField(new LongField(TiffTag.JPEG_INTERCHANGE_FORMAT_LENGTH.getValue(), new int[]{writeByteCount}));
}
}
/* Another flavor of the old style JPEG compression type 6 contains separate tables */
TiffField<?> jpegTable = ifd.removeField(TiffTag.JPEG_DC_TABLES);
if(jpegTable != null) {
try {
ifd.addField(copyJpegHufTable(rin, rout, jpegTable, (int)rout.getStreamPointer()));
} catch(EOFException ex) {;}
}
jpegTable = ifd.removeField(TiffTag.JPEG_AC_TABLES);
if(jpegTable != null) {
try {
ifd.addField(copyJpegHufTable(rin, rout, jpegTable, (int)rout.getStreamPointer()));
} catch(EOFException ex) {;}
}
jpegTable = ifd.removeField(TiffTag.JPEG_Q_TABLES);
if(jpegTable != null) {
try {
ifd.addField(copyJpegQTable(rin, rout, jpegTable, (int)rout.getStreamPointer()));
} catch(EOFException ex) {;}
}
/* End of code to work with old-style JPEG compression */
// Return the actual stream position (we may have lost track of it)
return (int)rout.getStreamPointer();
}
// Copy a list of IFD and associated image data if any
private static int copyPages(List<IFD> list, int writeOffset, RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
// Write the first page data
writeOffset = copyPageData(list.get(0), writeOffset, rin, rout);
// Then write the first IFD
writeOffset = list.get(0).write(rout, writeOffset);
// We are going to write the remaining image pages and IFDs if any
for(int i = 1; i < list.size(); i++) {
writeOffset = copyPageData(list.get(i), writeOffset, rin, rout);
// Tell the IFD to update next IFD offset for the following IFD
list.get(i-1).setNextIFDOffset(rout, writeOffset);
writeOffset = list.get(i).write(rout, writeOffset);
}
return writeOffset;
}
/**
* Extracts ICC_Profile from certain page of TIFF if any
*
* @param pageNumber page number from which to extract ICC_Profile
* @param rin RandomAccessInputStream for the input TIFF
* @return a byte array for the extracted ICC_Profile or null if none exists
* @throws Exception
*/
public static byte[] extractICCProfile(int pageNumber, RandomAccessInputStream rin) throws Exception {
// Read pass image header
int offset = readHeader(rin);
// Read the IFDs into a list first
List<IFD> ifds = new ArrayList<IFD>();
readIFDs(ifds, offset, rin);
if(pageNumber < 0 || pageNumber >= ifds.size())
throw new IllegalArgumentException("pageNumber " + pageNumber + " out of bounds: 0 - " + (ifds.size() - 1));
IFD workingPage = ifds.get(pageNumber);
TiffField<?> f_iccProfile = workingPage.getField(TiffTag.ICC_PROFILE);
if(f_iccProfile != null) {
return (byte[])f_iccProfile.getData();
}
return null;
}
public static byte[] extractICCProfile(RandomAccessInputStream rin) throws Exception {
return extractICCProfile(0, rin);
}
public static IRBThumbnail extractThumbnail(int pageNumber, RandomAccessInputStream rin) throws IOException {
// Read pass image header
int offset = readHeader(rin);
// Read the IFDs into a list first
List<IFD> ifds = new ArrayList<IFD>();
readIFDs(ifds, offset, rin);
if(pageNumber < 0 || pageNumber >= ifds.size())
throw new IllegalArgumentException("pageNumber " + pageNumber + " out of bounds: 0 - " + (ifds.size() - 1));
IFD workingPage = ifds.get(pageNumber);
TiffField<?> f_photoshop = workingPage.getField(TiffTag.PHOTOSHOP);
if(f_photoshop != null) {
byte[] data = (byte[])f_photoshop.getData();
IRB irb = new IRB(data);
if(irb.containsThumbnail()) {
IRBThumbnail thumbnail = irb.getThumbnail();
return thumbnail;
}
}
return null;
}
public static IRBThumbnail extractThumbnail(RandomAccessInputStream rin) throws IOException {
return extractThumbnail(0, rin);
}
public static void extractThumbnail(RandomAccessInputStream rin, String pathToThumbnail) throws IOException {
IRBThumbnail thumbnail = extractThumbnail(rin);
if(thumbnail != null) {
String outpath = "";
if(pathToThumbnail.endsWith("\\") || pathToThumbnail.endsWith("/"))
outpath = pathToThumbnail + "photoshop_thumbnail.jpg";
else
outpath = pathToThumbnail.replaceFirst("[.][^.]+$", "") + "_photoshop_t.jpg";
FileOutputStream fout = new FileOutputStream(outpath);
if(thumbnail.getDataType() == IRBThumbnail.DATA_TYPE_KJpegRGB) {
fout.write(thumbnail.getCompressedImage());
} else {
ImageWriter writer = ImageIO.getWriter(ImageType.JPG);
try {
writer.write(thumbnail.getRawImage(), fout);
} catch (Exception e) {
throw new IOException("Writing thumbnail failed!");
}
}
fout.close();
}
}
public static Collection<BufferedImage> extractThumbnails(RandomAccessInputStream rin) throws IOException {
Collection<BufferedImage> thumbnails = Collections.emptyList();
Thumbnail thumbnail = extractThumbnail(rin);
if(thumbnail != null)
thumbnails.add(thumbnail.getAsBufferedImage());
return thumbnails;
}
public static void finishInsert(RandomAccessOutputStream rout, List<IFD> list) throws IOException {
// Reset pageNumber and total pages
for(int i = 0; i < list.size(); i++) {
int offset = list.get(i).getField(TiffTag.PAGE_NUMBER).getDataOffset();
rout.seek(offset);
rout.writeShort((short)i); // Update page number for this page
rout.writeShort((short)list.size()); // Update total page number
}
// Link the IFDs
for(int i = 0; i < list.size() - 1; i++)
list.get(i).setNextIFDOffset(rout, list.get(i+1).getStartOffset());
int firstIFDOffset = list.get(0).getStartOffset();
writeToStream(rout, firstIFDOffset);
}
public static void finishWrite(RandomAccessOutputStream rout, List<IFD> list) throws IOException {
finishInsert(rout, list);
}
// Used to calculate how many bytes to read in case we have only one strip or tile
private static int[] getBytes2Read(IFD ifd) {
// Let's calculate how many bytes we are supposed to read
TiffField<?> tiffField = ifd.getField(TiffTag.IMAGE_WIDTH);
int imageWidth = tiffField.getDataAsLong()[0];
tiffField = ifd.getField(TiffTag.IMAGE_LENGTH);
int imageHeight = tiffField.getDataAsLong()[0];
// For YCbCr image only
int horizontalSampleFactor = 2; // Default 2X2
int verticalSampleFactor = 2; // Not 1X1
int photoMetric = ifd.getField(TiffTag.PHOTOMETRIC_INTERPRETATION).getDataAsLong()[0];
// Correction for imageWidth and imageHeight for YCbCr image
if(photoMetric == TiffFieldEnum.PhotoMetric.YCbCr.getValue()) {
TiffField<?> f_YCbCrSubSampling = ifd.getField(TiffTag.YCbCr_SUB_SAMPLING);
if(f_YCbCrSubSampling != null) {
int[] sampleFactors = f_YCbCrSubSampling.getDataAsLong();
horizontalSampleFactor = sampleFactors[0];
verticalSampleFactor = sampleFactors[1];
}
imageWidth = ((imageWidth + horizontalSampleFactor - 1)/horizontalSampleFactor)*horizontalSampleFactor;
imageHeight = ((imageHeight + verticalSampleFactor - 1)/verticalSampleFactor)*verticalSampleFactor;
}
int samplesPerPixel = 1;
tiffField = ifd.getField(TiffTag.SAMPLES_PER_PIXEL);
if(tiffField != null) {
samplesPerPixel = tiffField.getDataAsLong()[0];
}
int bitsPerSample = 1;
tiffField = ifd.getField(TiffTag.BITS_PER_SAMPLE);
if(tiffField != null) {
bitsPerSample = tiffField.getDataAsLong()[0];
}
int tileWidth = -1;
int tileLength = -1;
TiffField<?> f_tileLength = ifd.getField(TiffTag.TILE_LENGTH);
TiffField<?> f_tileWidth = ifd.getField(TiffTag.TILE_WIDTH);
if(f_tileWidth != null) {
tileWidth = f_tileWidth.getDataAsLong()[0];
tileLength = f_tileLength.getDataAsLong()[0];
}
int rowsPerStrip = imageHeight;
int rowWidth = imageWidth;
TiffField<?> f_rowsPerStrip = ifd.getField(TiffTag.ROWS_PER_STRIP);
if(f_rowsPerStrip != null) rowsPerStrip = f_rowsPerStrip.getDataAsLong()[0];
if(rowsPerStrip > imageHeight) rowsPerStrip = imageHeight;
if(tileWidth > 0) {
rowsPerStrip = tileLength;
rowWidth = tileWidth;
}
int planaryConfiguration = 1;
tiffField = ifd.getField(TiffTag.PLANAR_CONFIGURATTION);
if(tiffField != null) planaryConfiguration = tiffField.getDataAsLong()[0];
int[] totalBytes2Read = new int[samplesPerPixel];
if(planaryConfiguration == 1)
totalBytes2Read[0] = ((rowWidth*bitsPerSample*samplesPerPixel + 7)/8)*rowsPerStrip;
else
totalBytes2Read[0] = totalBytes2Read[1] = totalBytes2Read[2] = ((rowWidth*bitsPerSample + 7)/8)*rowsPerStrip;
if(photoMetric == TiffFieldEnum.PhotoMetric.YCbCr.getValue()) {
if(samplesPerPixel != 3) samplesPerPixel = 3;
int[] sampleBytesPerRow = new int[samplesPerPixel];
sampleBytesPerRow[0] = (bitsPerSample*rowWidth + 7)/8;
sampleBytesPerRow[1] = (bitsPerSample*rowWidth/horizontalSampleFactor + 7)/8;
sampleBytesPerRow[2] = sampleBytesPerRow[1];
int[] sampleRowsPerStrip = new int[samplesPerPixel];
sampleRowsPerStrip[0] = rowsPerStrip;
sampleRowsPerStrip[1] = rowsPerStrip/verticalSampleFactor;
sampleRowsPerStrip[2]= sampleRowsPerStrip[1];
totalBytes2Read[0] = sampleBytesPerRow[0]*sampleRowsPerStrip[0];
totalBytes2Read[1] = sampleBytesPerRow[1]*sampleRowsPerStrip[1];
totalBytes2Read[2] = totalBytes2Read[1];
if(tiffField != null) planaryConfiguration = tiffField.getDataAsLong()[0];
if(planaryConfiguration == 1)
totalBytes2Read[0] = totalBytes2Read[0] + totalBytes2Read[1] + totalBytes2Read[2];
}
return totalBytes2Read;
}
/**
* Get the total number of pages for the TIFF image
*
* @param rin RandomAccessInputStream to read the image
* @return total number of pages for the image
* @throws IOException
*/
public static int getPageCount(RandomAccessInputStream rin) throws IOException {
// Keep track of the current stream pointer
long streamPointer = rin.getStreamPointer();
// Go the the stream head
rin.seek(STREAM_HEAD);
List<IFD> list = new ArrayList<IFD>();
readIFDs(list, rin);
// Reset stream pointer
rin.seek(streamPointer);
return list.size();
}
private static int getRowWidth(IFD ifd) {
// Get image dimension first
TiffField<?> tiffField = ifd.getField(TiffTag.IMAGE_WIDTH);
int imageWidth = tiffField.getDataAsLong()[0];
// For YCbCr image only
int horizontalSampleFactor = 2; // Default 2X2
int photoMetric = ifd.getField(TiffTag.PHOTOMETRIC_INTERPRETATION).getDataAsLong()[0];
// Correction for imageWidth and imageHeight for YCbCr image
if(photoMetric == TiffFieldEnum.PhotoMetric.YCbCr.getValue()) {
TiffField<?> f_YCbCrSubSampling = ifd.getField(TiffTag.YCbCr_SUB_SAMPLING);
if(f_YCbCrSubSampling != null) {
int[] sampleFactors = f_YCbCrSubSampling.getDataAsLong();
horizontalSampleFactor = sampleFactors[0];
}
imageWidth = ((imageWidth + horizontalSampleFactor - 1)/horizontalSampleFactor)*horizontalSampleFactor;
}
int rowWidth = imageWidth;
int tileWidth = -1;
TiffField<?> f_tileWidth = ifd.getField(TiffTag.TILE_WIDTH);
if(f_tileWidth != null) {
tileWidth = f_tileWidth.getDataAsLong()[0];
if(tileWidth > 0)
rowWidth = tileWidth;
}
return rowWidth;
}
// Calculate the expected StripByteCounts values for uncompressed image
public static int[] getUncompressedStripByteCounts(IFD ifd, int strips) {
// Get image dimension first
TiffField<?> tiffField = ifd.getField(TiffTag.IMAGE_WIDTH);
int imageWidth = tiffField.getDataAsLong()[0];
tiffField = ifd.getField(TiffTag.IMAGE_LENGTH);
int imageHeight = tiffField.getDataAsLong()[0];
// For YCbCr image only
int horizontalSampleFactor = 2; // Default 2X2
int verticalSampleFactor = 2; // Not 1X1
tiffField = ifd.getField(TiffTag.PHOTOMETRIC_INTERPRETATION);
int photoMetric = PhotoMetric.WHITE_IS_ZERO.getValue();
if(tiffField != null)
photoMetric = tiffField.getDataAsLong()[0];
// Correction for imageWidth and imageHeight for YCbCr image
if(photoMetric == TiffFieldEnum.PhotoMetric.YCbCr.getValue()) {
TiffField<?> f_YCbCrSubSampling = ifd.getField(TiffTag.YCbCr_SUB_SAMPLING);
if(f_YCbCrSubSampling != null) {
int[] sampleFactors = f_YCbCrSubSampling.getDataAsLong();
horizontalSampleFactor = sampleFactors[0];
verticalSampleFactor = sampleFactors[1];
}
imageWidth = ((imageWidth + horizontalSampleFactor - 1)/horizontalSampleFactor)*horizontalSampleFactor;
imageHeight = ((imageHeight + verticalSampleFactor - 1)/verticalSampleFactor)*verticalSampleFactor;
}
int samplesPerPixel = 1;
tiffField = ifd.getField(TiffTag.SAMPLES_PER_PIXEL);
if(tiffField != null) {
samplesPerPixel = tiffField.getDataAsLong()[0];
}
int bitsPerSample = 1;
tiffField = ifd.getField(TiffTag.BITS_PER_SAMPLE);
if(tiffField != null) {
bitsPerSample = tiffField.getDataAsLong()[0];
}
int tileWidth = -1;
int tileLength = -1;
TiffField<?> f_tileLength = ifd.getField(TiffTag.TILE_LENGTH);
TiffField<?> f_tileWidth = ifd.getField(TiffTag.TILE_WIDTH);
if(f_tileWidth != null) {
tileWidth = f_tileWidth.getDataAsLong()[0];
tileLength = f_tileLength.getDataAsLong()[0];
}
int rowsPerStrip = imageHeight;
int rowWidth = imageWidth;
TiffField<?> f_rowsPerStrip = ifd.getField(TiffTag.ROWS_PER_STRIP);
if(f_rowsPerStrip != null) rowsPerStrip = f_rowsPerStrip.getDataAsLong()[0];
if(rowsPerStrip > imageHeight) rowsPerStrip = imageHeight;
if(tileWidth > 0) {
rowsPerStrip = tileLength;
rowWidth = tileWidth;
}
int bytesPerRow = ((bitsPerSample*rowWidth*samplesPerPixel + 7)/8);
int planaryConfiguration = 1;
tiffField = ifd.getField(TiffTag.PLANAR_CONFIGURATTION);
if(tiffField != null) planaryConfiguration = tiffField.getDataAsLong()[0];
if(planaryConfiguration == 2) {
bytesPerRow = (bitsPerSample*rowWidth + 7)/8;
}
int bytesPerStrip = bytesPerRow*rowsPerStrip;
int[] counts = new int[strips];
if(photoMetric != TiffFieldEnum.PhotoMetric.YCbCr.getValue()) {
// Fill the StripByteCounts first
Arrays.fill(counts, bytesPerStrip);
// We may need to adjust the last strip in case we are dealing with stripped structure
if(tileWidth < 0) { // Stripped structure, last strip/strips may be smaller
int lastStripBytes = bytesPerRow*imageHeight - bytesPerStrip*(strips - 1);
counts[counts.length - 1] = lastStripBytes;
// Structure |sample1sample1 ...|sample2sample2 ...| ...
if(planaryConfiguration == 2) {
int stripsPerSample = strips/samplesPerPixel;
lastStripBytes = bytesPerRow*imageHeight - bytesPerStrip*(stripsPerSample - 1);
if(lastStripBytes > 0) {
for(int i = 0, stripOffset = stripsPerSample - 1; i < samplesPerPixel; i++) {
counts[stripOffset] = lastStripBytes;
stripOffset += stripsPerSample;
}
}
}
}
} else { // Deal with YCbCr down sampling
if(samplesPerPixel != 3) samplesPerPixel = 3;
int[] sampleBytesPerRow = new int[samplesPerPixel];
sampleBytesPerRow[0] = (bitsPerSample*rowWidth + 7)/8;
sampleBytesPerRow[1] = (bitsPerSample*rowWidth/horizontalSampleFactor + 7)/8;
sampleBytesPerRow[2] = sampleBytesPerRow[1];
int[] sampleRowsPerStrip = new int[samplesPerPixel];
sampleRowsPerStrip[0] = rowsPerStrip;
sampleRowsPerStrip[1] = rowsPerStrip/verticalSampleFactor;
sampleRowsPerStrip[2]= sampleRowsPerStrip[1];
int[] columnHeight = new int[samplesPerPixel];
columnHeight[0] = imageHeight;
columnHeight[1] = imageHeight/verticalSampleFactor;
columnHeight[2] = columnHeight[1];
if(planaryConfiguration == 1) {
bytesPerStrip = sampleBytesPerRow[0]*sampleRowsPerStrip[0] + sampleBytesPerRow[1]*sampleRowsPerStrip[1] + sampleBytesPerRow[2]*sampleRowsPerStrip[2];
Arrays.fill(counts, bytesPerStrip);
if(tileWidth < 0) { // Stripped structure, last strip may be smaller
int lastStripBytes = (sampleBytesPerRow[0]*columnHeight[0] + sampleBytesPerRow[1]*columnHeight[1] + sampleBytesPerRow[2]*columnHeight[2]) - bytesPerStrip*(strips - 1);
counts[counts.length - 1] = lastStripBytes;
}
} else { // Separate sample planes -
int[] sampleBytesPerStrip = new int[samplesPerPixel];
sampleBytesPerStrip[0] = sampleRowsPerStrip[0]*sampleBytesPerRow[0];
sampleBytesPerStrip[1] = sampleRowsPerStrip[1]*sampleBytesPerRow[1];
sampleBytesPerStrip[2] = sampleBytesPerStrip[1];
int stripsPerSample = strips/samplesPerPixel;
int startOffset = 0;
int endOffset = stripsPerSample;
for(int i = 0; i < samplesPerPixel; i++) {
Arrays.fill(counts, startOffset, endOffset, sampleBytesPerStrip[i]);
startOffset = endOffset;
endOffset += stripsPerSample;
}
if(tileWidth < 0) { // Stripped structure, last strip may be smaller
int[] lastStripBytes = new int[samplesPerPixel];
lastStripBytes[0] = sampleBytesPerRow[0]*columnHeight[0] - sampleBytesPerStrip[0]*(stripsPerSample - 1);
lastStripBytes[1] = sampleBytesPerRow[1]*columnHeight[1] - sampleBytesPerStrip[1]*(stripsPerSample - 1);
lastStripBytes[2] = lastStripBytes[1];
startOffset = stripsPerSample - 1;
for(int i = 0; i < samplesPerPixel; i++) {
counts[startOffset] = lastStripBytes[i];
startOffset += stripsPerSample;
}
}
}
}
return counts;
}
public static void insertComments(List<String> comments, RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
insertComments(comments, 0, rin, rout);
}
public static void insertComments(List<String> comments, int pageNumber, RandomAccessInputStream rin, RandomAccessOutputStream rout) throws IOException {
int offset = copyHeader(rin, rout);
// Read the IFDs into a list first
List<IFD> ifds = new ArrayList<IFD>();
readIFDs(ifds, offset, rin);