Question

All I need is to take TIFF file, open it and copy to new file while using G4 compression.

So, I took LibTiff.Net and TiffCP utility. Did my best to convert code from TIffCP and here is function I have:

public static byte[] ConvertToG4Tiff(byte[] input)
{
    var c = new Copier();

    // Set compression to g4
    if (!c.ProcessCompressOptions("g4")) return null;

    // Open output tiff
    var memoryStream = new MemoryStream();
    var tiffStream = new TiffStream();
    using (var outImage = Tiff.ClientOpen(string.Empty, "w", memoryStream, tiffStream))
    {
        using (var inImage = Tiff.ClientOpen(string.Empty, "read", new MemoryStream(input), new TiffStream()))
        {
            if (inImage == null) return null;

            int totalPages = inImage.NumberOfDirectories();
            for (var i = 0; i < totalPages;)
            {
                c.m_config = PlanarConfig.UNKNOWN;
                c.m_compression = c.m_defcompression;
                c.m_predictor = c.m_defpredictor;
                c.m_fillorder = 0;
                c.m_rowsperstrip = 0;
                c.m_tilewidth = -1;
                c.m_tilelength = -1;
                c.m_g3opts = c.m_defg3opts;

                if (!inImage.SetDirectory((short)i)) return null;
                if (!c.Copy(inImage, outImage) || !outImage.WriteDirectory()) return null;

                i++;
            }
        }

        var retVal = new byte[tiffStream.Size(memoryStream)];
        tiffStream.Read(memoryStream, retVal, 0, retVal.Length);
        return retVal;
    }
}

I think last 3 lines is where I messed up. I do get valid byte array back (There is data and it's about 10% of original uncompressed TIFF)

When I try to open it with code again - it won't open. Passing this new array through this same function will not work. Opened object is NULL.

What did I do wrong?

Was it helpful?

Solution

You are supposed to use memoryStream to retrieve compressed data. Do not use tiffStream for anything in a code like this.

So, the

var retVal = new byte[tiffStream.Size(memoryStream)];
tiffStream.Read(memoryStream, retVal, 0, retVal.Length);
return retVal;

should probably be changed to

var retVal = memoryStream.ToArray();
return retVal;

Please also note that your code won't convert data so if input bytes are not 1bpp raster than the code will fail.

It's unclear why would you want to pass compressed data to the same code.

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