C# – Edit multipage TIFF image using System.Drawing

csystem.drawingtiffwinforms

I'm tring to edit multipage tiff by creating Graphics from the image, but i encountered the error message: “A Graphics object cannot be created from an image that has an indexed pixel format.”

How can i edit multipage tiff?

Best Answer

I wrote something to extract single pages from a multipage tiff file.

// Load as Bitmap
using (Bitmap bmp = new Bitmap(file))
{
    // Get pages in bitmap
    int frames = bmp.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
    bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, tiffpage);
    if (bmp.PixelFormat != PixelFormat.Format1bppIndexed)
    {
        using (Bitmap bmp2 = new Bitmap(bmp.Width, bmp.Height))
        {
            bmp2.Palette = bmp.Palette;
            bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
            // create graphics object for new bitmap
            using (Graphics g = Graphics.FromImage(bmp2))
            {
                // copy current page into new bitmap
                g.DrawImageUnscaled(bmp, 0, 0);

                                // do whatever you migth to do
                ...

            }
        }
    }
}

The snippet loads the tif file and extracts the one page (number in variable tiffpage) into a new bitmap. This is not indexed and an graphics object can be created.