Question

NET library a retrieve count of pages in multi tiff. I use sample from http://bitmiracle.com/libtiff/help/retrieve-number-of-pages-in-tiff-image.aspx.

    public int GetNumberOfPages(Tiff image)
    {
        int pageCount = 0;
        do
        {
            ++pageCount;
        } while (image.ReadDirectory());

        return pageCount;
    }

    [TestMethod]
    public void GetNumberOfPages()
    {
        using (Tiff tiffFromFile = Tiff.Open(@"test.tif", "r"))
        {
            int numberOfPages = GetNumberOfPages(tiffFromFile);
        }

    }

I get exception: Cannot write to a closed TextWriter.

StackTrace:

at System.IO.__Error.WriterClosed()
   at System.IO.StringWriter.Write(String value)
   at Microsoft.VisualStudio.TestTools.TestTypes.Unit.ThreadSafeStringWriter.Write(String value)
   at System.IO.TextWriter.Write(String format, Object arg0)
   at System.IO.TextWriter.SyncTextWriter.Write(String format, Object arg0)
   at BitMiracle.LibTiff.Classic.TiffErrorHandler.WarningHandler(Tiff tif, String method, String format, Object[] args)
   at BitMiracle.LibTiff.Classic.Tiff.WarningExt(Tiff tif, Object clientData, String method, String format, Object[] args)
   at BitMiracle.LibTiff.Classic.Tiff.ReadDirectory()

The code is identical from sample. I can’t find root of this problem.

Was it helpful?

Solution

I would guess that the problem may be related to an unsupported image type or errors in the tiff file you are passing it. The LibTiff docs talk about adding a custom handler if you want to respond to errors. Not having used that library before, I can't say for certain what happened. I would guess that maybe there was an error in the Open, but without having a handler, it ate the error. Then when you try to ReadDirectory the file is already closed. This is just a guess. I would recommend you add an error handler and see what is going on.

http://bitmiracle.com/libtiff/help/tiff.seterrorhandler.aspx

EDIT:

I looked back at the sample page. They actually give two ways of reading the number of pages. Have you tried the simpler way to see if that fails the same way? To calculate number of pages in a TIFF image the Tiff.NumberOfDirectories() method or a simple loop that traverses directories can be used. This sample shows both methods.

You should be able to turn your method into this:

public short GetNumberOfPages(Tiff image)
{
    return image.NumberOfDirectories()
}

If you are still having issues, try a different image that you know is valid and has multiple pages so that you can rule out the image issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top