Skip to main content

C# helper class to merge TIFF files into a single, multipage TIFF file.

using System;
using System.Drawing.Imaging;
using System.IO;

//
// ASP.NET C# Helper Class to merge TIFF files into a single multipage TIFF
//
// A small yet useful Helper Class written in C-Sharp that can be used to merge
// multiple TIFF image files into a single multipage TIFF file
//
// https://www.ryadel.com/en/asp-net-c-sharp-merge-tiff-files-into-single-multipage-tif/
//

namespace Ryadel.Components.Media
{
    /// <summary>
    /// A small helper class to handle TIFF files
    /// </summary>
    public static class TiffHelper
    {
        /// <summary>
        /// Merges multiple TIFF files (including multipage TIFFs) into a single multipage TIFF file.
        /// </summary>
        public static byte[] MergeTiff(params byte[][] tiffFiles)
        {
            byte[] tiffMerge = null;
            using (var msMerge = new MemoryStream())
            {
                foreach (var tiffFile in tiffFiles)
                {
                    using (var ms = new MemoryStream(tiffFile))
                    {
                        //Get the frame dimension list from the image of the file and
                        using (System.Drawing.Image tiffImage = System.Drawing.Image.FromStream(ms))
                        {
                            //get the globally unique identifier (GUID)
                            Guid objGuid = tiffImage.FrameDimensionsList[0];
                            //create the frame dimension
                            FrameDimension dim = new FrameDimension(objGuid);
                            //Gets the total number of frames in the .tiff file
                            int pageNum = tiffImage.GetFrameCount(dim);
                            foreach (Guid guid in tiffImage.FrameDimensionsList)
                            {
                                for (int index = 0; index < pageNum; index++)
                                {
                                    FrameDimension currentFrame = new FrameDimension(guid);
                                    tiffImage.SelectActiveFrame(currentFrame, index);
                                    tiffImage.Save(msMerge, ImageFormat.Tiff);
                                }
                            }
                        }
                    }
                }

                msMerge.Position = 0;
                tiffMerge = msMerge.ToArray();
            }

            return tiffMerge;
        }
    }
}