Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Utility to combine multiple TIFFs into a single multi-page TIFF
public class ImageUtilities
{
//refrence https://stackoverflow.com/questions/398388/convert-bitmaps-to-one-multipage-tiff-image-in-net-2-0
private const string Encoder = "image/tiff";
public static Image CombineFiles(string[] inputFiles, string output)
{
Image multiPageFile = null;
byte[] ba = null;
var tiffCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(t => t.MimeType == Encoder);
using (var ms = new MemoryStream())
{
for (var i = 0; i < inputFiles.Length; ++i)
{
var firstPage = i == 0;
var inputFile = inputFiles[i];
multiPageFile = LoadImage(inputFile, firstPage, multiPageFile, tiffCodec, ms);
}
ba = ms.ToArray();
}
File.WriteAllBytes(output, ba);
return multiPageFile;
}
private static Image LoadImage(string inputFile, bool firstPage, Image multiPageFile, ImageCodecInfo tiffCodec, MemoryStream ms)
{
using (var inputImage = Image.FromFile(inputFile))
{
using (var byteStream = new MemoryStream())
{
inputImage.Save(byteStream, ImageFormat.Tiff);
if (firstPage)
{
multiPageFile = Image.FromStream(byteStream);
multiPageFile = SaveImages(tiffCodec, ms, multiPageFile, null);
}
else
{
using (var tiffImage = Image.FromStream(byteStream))
{
multiPageFile = SaveImages(tiffCodec, ms, tiffImage, multiPageFile);
}
}
}
}
return multiPageFile;
}
private static Image SaveImages(ImageCodecInfo tiffCodec,
Stream outputStream,
Image tiffImage,
Image firstImage)
{
using (var encParameters = new EncoderParameters(3))
{
if (firstImage == null)
{
encParameters.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag
, (long)EncoderValue.MultiFrame // 18L
);
}
else
{
encParameters.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag
, (long)EncoderValue.FrameDimensionPage // 23L
);
}
encParameters.Param[1] = new EncoderParameter(
System.Drawing.Imaging.Encoder.ColorDepth, 24L
);
encParameters.Param[2] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Compression
, (long)EncoderValue.CompressionLZW
);
if (firstImage == null)
{
firstImage = tiffImage;
((Bitmap)tiffImage).SetResolution(96, 96);
firstImage.Save(outputStream, tiffCodec, encParameters);
}
else
{
((Bitmap)tiffImage).SetResolution(96, 96);
firstImage.SaveAdd(tiffImage, encParameters);
}
encParameters.Param[0]?.Dispose();
encParameters.Param[1]?.Dispose();
encParameters.Param[2]?.Dispose();
}
return firstImage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.