Convert bitmaps to one multipage TIFF image in .NET 2.0

mirezus picture mirezus · Dec 29, 2008 · Viewed 62k times · Source

How can i convert an array of bitmaps into a brand new image of TIFF format, adding all the bitmaps as frames in this new tiff image?

using .NET 2.0.

Answer

Otávio Décio picture Otávio Décio · Dec 29, 2008

Start with the first bitmap by putting it into an Image object

Bitmap bitmap = (Bitmap)Image.FromFile(file);

Save the bitmap to memory as tiff

MemoryStream byteStream = new MemoryStream();
bitmap.Save(byteStream, ImageFormat.Tiff);

Put Tiff into another Image object

Image tiff = Image.FromStream(byteStream)

Prepare encoders:

var encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");

EncoderParameters encoderParams = new EncoderParameters(2);
encoderParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone);
encoderParams.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);

Save to file:

tiff.Save(sOutFilePath, encoderInfo, encoderParams);

For subsequent pages, prepare encoders:

EncoderParameters EncoderParams = new EncoderParameters(2);
EncoderParameter SaveEncodeParam = new EncoderParameter(
     Encoder.SaveFlag, 
     (long)EncoderValue.FrameDimensionPage);
EncoderParameter CompressionEncodeParam = new EncoderParameter(
     Encoder.Compression, (long)EncoderValue.CompressionNone);
EncoderParams.Param[0] = CompressionEncodeParam;
EncoderParams.Param[1] = SaveEncodeParam;
tiff.SaveAdd(/* next image as tiff - do the same as above with memory */, EncoderParams);

Finally flush the file:

EncoderParameter SaveEncodeParam = new EncoderParameter(
     Encoder.SaveFlag, (long)EncoderValue.Flush);
EncoderParams = new EncoderParameters(1);
EncoderParams.Param[0] = SaveEncodeParam;
tiff.SaveAdd(EncoderParams);

That should get you started.