C# Generic GDI+ Error when using Image.Save()

2019-02-28 09:52发布

I am a relative novice with imaging in C#. This is my first question on this board after a very long time of being a member. I hope it can help me get through this tricky scenario.

I need to read the contents (frames) of a Multi Page TIFF, saving each one into a List and finally returning it to then do some work with it.

Heres my code so far

public static  List<Image> GetAllPages(string file)
{
    images = new List<Image>();
    using (Image img = Image.FromFile(file))
    {
        try
        {
            for (int i = 0; i < img.GetFrameCount(FrameDimension.Page); i++)
            {
                img.SelectActiveFrame(FrameDimension.Page, i);
                MemoryStream byteStream = new MemoryStream();
                img.Save(byteStream, ImageFormat.Tiff);
                images.Add(Image.FromStream(byteStream));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    return images;
}

IMPORTANT - This actually works like a charm when executing on Windows 7. However, when attempting the same on a Windows XP I get the seemedly well known Generic GDI+ error.

Is there anything obvious i am missing here? If not, would there be any other, more efficient way to return a list of images, extracted from a multi page tiff?

I would greatly appreciate any help anyone can give.

1条回答
三岁会撩人
2楼-- · 2019-02-28 10:28

There are 2 useful bits of information in the comment by Hans Passant. First, the TIFF format supports countless sub-types and variations not all of which are supported by GDI+. Second, GDI+ was improved after XP, but not everywhere.

Your code does work on both Windows XP and Windows 7, but only with the right input TIFF files.

I tested it using .NET 2.0 and .NET 4.0 programs with 2 input files. The first file had 6 pages, all of which were encoded with LZW compression. This file worked on both Windows 7 and XP.

The second file had 11 pages with 11 different types of encoding. On Windows XP, only 7 pages out of 11 were loaded correctly. On Windows 7, even fewer pages worked, but the JPEG compression in particular worked correctly although it failed under XP.

Windows 8.1 fared better than both and managed to load 8 pages correctly.

You can find the files along with a list of compression types used on this page: http://support.leadtools.com/CS/forums/44475/ShowPost.aspx

Of course there are other TIFF sub-types, most of which are not supported by GDI+ natively, but these 11 are among the more common formats.

This leaves us with the problem of getting your files to work on Windows XP. Since they work on Windows 7, there's a strong possibility you have a TIF sub-type that works on Windows 7 but not XP such as JPEG compression. If that's the case, .NET alone will not be enough and you might have to use a dedicated imaging or TIFF library to load such files.

查看更多
登录 后发表回答