Convert multipage TIFF to PNG .Net

mytwocents picture mytwocents · Aug 25, 2010 · Viewed 7.2k times · Source

I am able to convert a single page TIFF to a PNG in .Net, however, how would I do this for a multipage TIFF?

Answer

Alyson Freitas picture Alyson Freitas · Nov 24, 2015

thanks @Tom Halladay

I'll provide a c# version of your code

private static Bitmap ConvertTiffToBitmapStream(byte[] tiffImage){
    System.Drawing.Image ImageBitmap = Bitmap.FromStream(new MemoryStream(tiffImage));
    int FrameCount = ImageBitmap.GetFrameCount(FrameDimension.Page);
    int RunningHeight = 0;
    int MaxWidth = 0;

    for (int MeasurementFrameIndex = 0; MeasurementFrameIndex <= FrameCount - 1; MeasurementFrameIndex++){
        ImageBitmap.SelectActiveFrame(FrameDimension.Page, MeasurementFrameIndex);
        RunningHeight += ImageBitmap.Height;
        MaxWidth = Math.Max(MaxWidth, ImageBitmap.Width);
    }

    Bitmap CombinedBitmap = new Bitmap(MaxWidth, RunningHeight);
    int RunningVerticalPosition = 0;

    for (int CombinationFrameIndex = 0; CombinationFrameIndex <= FrameCount - 1; CombinationFrameIndex++){
        ImageBitmap.SelectActiveFrame(FrameDimension.Page, CombinationFrameIndex);
        EmbedBitmap(new Bitmap(ImageBitmap), ref CombinedBitmap, RunningVerticalPosition);
        RunningVerticalPosition += ImageBitmap.Height + 1;
    }
    return CombinedBitmap;
}

private static void EmbedBitmap(Bitmap SourceBitmap, ref Bitmap DestinationBitmap, int VerticalPosition){
    Rectangle SourceRectangle = new Rectangle(new Point(0, 0), new Size(SourceBitmap.Width, SourceBitmap.Height));
    Rectangle DestinationRectangle = new Rectangle(new Point(0, VerticalPosition), new Size(SourceBitmap.Width, SourceBitmap.Height));

    using (Graphics Canvas = Graphics.FromImage(DestinationBitmap)){
        Canvas.DrawImage(SourceBitmap, DestinationRectangle, SourceRectangle, GraphicsUnit.Pixel);
    }
}