Support Center

Efficiently merging multiple image files in C#

Last Updated: May 09, 2013 09:45AM EDT
A common question is how to combine multiple image files into a single file. This can be done in several ways but the code below is the most efficient way to do so. This code will open images in any supported format and then save them as a multi page TIFF file as it uses the TifEncoder class. You could of course use some other encoder that supports multiple pages such as PDF, PNG, etc.

private void CombineFiles(string outputFilename, string[] inputFiles)
{
   // Create the stream for out output file
   FileStream outputStream = new FileStream(outputFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite,       FileShare.Read);

   // Create our Output Decoder
   TifEncoder encoder = new TifEncoder();

   foreach (string file in inputFiles)
   {
      // Open the input file, read each page and save it to the output file
      SeekableReadOnlyStream inputStream = new SeekableReadOnlyStream(new FileStream(file,   FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read));
      ImDecoder decoder = RegisteredDecoders.GetDecoder(inputStream);

      if (decoder == null)
         throw new ImageLoadException("Unknown or unsupported Image Format");

      decoder.Stream = inputStream;

     int pages = decoder.Pages;

     for (int i = 0; i < pages; i++)
     {
        decoder.Page = i;
        ImImage img = decoder.Load(null);

        outputStream.Seek(0, SeekOrigin.Begin);
        encoder.Save(outputStream, img, null);

        // Clean up the image now that its saved
        img.Dispose();
     }

     // Close our stream now that we have read all the images
     inputStream.Close();
     inputStream.Dispose();
   }

   //Done with the output File as well so close it
   outputStream.Close();
   outputStream.Dispose();

   encoder.Dispose();
}

Contact Us