title: How to combine multiple multi-page tif files into a single tif
body: <p>I am trying to take multiple multi-page .tif files and combine them into a single multi-page tif file.</p>
  
  <p>I found some code in this <a href="https://stackoverflow.com/questions/3165792/how-to-combine-two-or-many-tiff-image-files-in-to-one-multipage-tiff-image-in-jav">question</a>, but it only seems to take the first page of each individual .tif file and create the new multi-page .tif with those first pages.</p>
  
  <p>Is there a small change I'm not seeing that would cause this same code to grab every page from the source .tif files and put them all into the combined .tif?</p>
  
  <p>To clarify, I would like the source files:</p>
  
  <ul>
  <li>SourceA.tif (3 pages)</li>
  <li>SourceB.tif (4 pages)</li>
  <li>SourceC.tif (1 page)</li>
  </ul>
  
  <p>to be combined into </p>
  
  <ul>
  <li>combined.tif (8 pages)</li>
  </ul>
  
  <p>I would also like to be able to specify a resolution and compression of the .tif, but I'm not sure if JAI supports that and it's not a necessity for a correct answer.</p>
  
  <p>The code from the referenced question, modified by me to load all the .tif files in a directory, is below for easy answering:</p>
  
  <pre><code>public static void main(String[] args) {
          String inputDir = "C:\\tifSources";
          File sourceDirectory = new File(inputDir);
          File file[] = sourceDirectory.listFiles();
          int numImages = file.length;
  
          BufferedImage image[] = new BufferedImage[numImages];
  
          try
          {
              for (int i = 0; i &lt; numImages; i++)
              {
                  SeekableStream ss = new FileSeekableStream(file[i]);
                  ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
                  PlanarImage op = new NullOpImage(decoder.decodeAsRenderedImage(0), null, null, OpImage.OP_IO_BOUND);
                  image[i] = op.getAsBufferedImage();
              }
  
              TIFFEncodeParam params = new TIFFEncodeParam();
              OutputStream out = new FileOutputStream(inputDir + "\\combined.tif"); 
              ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
              List&lt;BufferedImage&gt; imageList = new ArrayList&lt;BufferedImage&gt;();   
              for (int i = 0; i &lt; numImages; i++)
              {
                  imageList.add(image[i]); 
              }
              params.setExtraImages(imageList.iterator()); 
              encoder.encode(image[0]); 
              out.close();
          }
          catch (Exception e)
          {
              System.out.println("Exception " + e);
          }
      }
  </code></pre>