Edit multipage TIFF image using System.Drawing

你离开我真会死。 提交于 2019-12-11 02:52:18

问题


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?


回答1:


The error : A Graphics object cannot be created from an image that has an indexed pixel format.

...has nothing to do with it being a multipage TIFF. An indexed image format means it has a palette of colours, e.g. it's a 256-colour image. A 1-bit image (B&W) would also count as having a palette of 2 colours.

You can't perform Graphics operations on images that use a palette, they'd need to be converted to 15-bit or more colour depth first.




回答2:


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.




回答3:


Here is a link to a CodeProject sample that includes code for converting a TIFF file to a normal Bitmap, which you can then work with like any other Bitmap:

http://www.codeproject.com/KB/GDI-plus/BitonalImageConverter.aspx




回答4:


I once wrote little utility to create encrypted pdfs from tiff images. Here is a piece of code to get pages from tiff image:

var bm= new System.Drawing.Bitmap('tif path');
var total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
for(var x=0;x<total;x++)
{
    bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page,x);
    var img=Image.GetInstance(bm,null,false);

    //do what ever you want with img object
}


来源:https://stackoverflow.com/questions/1327821/edit-multipage-tiff-image-using-system-drawing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!