How to compress tiff multipage image in c#

38 Views Asked by At

I am using BitMiracle.LibTiff.Classic library but it does not work as the compress multipage tiff file shows "windows photo viewer cant open the picture because the file appears to be damaged,corrupted or too large". Here is my sample image in the attachment name as 638306509065230404.tiff and output file name as test.tiff

private static void Test()
        {
            string inputFilePath = "D:\\Rohit\\638306509065230404.tiff";
            string outputFilePath = "D:\\Rohit\\test.tiff";

            using (Tiff inputTiff = Tiff.Open(inputFilePath, "r"))
            {
                if (inputTiff == null)
                {
                    Console.WriteLine("Failed to open input TIFF file.");
                    return;
                }

                using (Tiff outputTiff = Tiff.Open(outputFilePath, "w"))
                {
                    if (outputTiff == null)
                    {
                        Console.WriteLine("Failed to create output TIFF file.");
                        return;
                    }

                    try
                    {
                        // Set compression to none
                        outputTiff.SetField(TiffTag.COMPRESSION, Compression.NONE);

                        // Set other required fields (adjust these values as needed)
                        outputTiff.SetField(TiffTag.IMAGEWIDTH, inputTiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt());
                        outputTiff.SetField(TiffTag.IMAGELENGTH, inputTiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt());
                        outputTiff.SetField(TiffTag.BITSPERSAMPLE, inputTiff.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt());

                        byte[] buffer = new byte[inputTiff.ScanlineSize()];

                        // Copy image data from the input TIFF to the output TIFF
                        for (int i = 0; i < inputTiff.NumberOfStrips(); i++)
                        {
                            inputTiff.ReadEncodedStrip(i, buffer, 0, buffer.Length);
                            outputTiff.WriteEncodedStrip(i, buffer, buffer.Length);
                        }

                        Console.WriteLine("Image copying completed successfully.");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: " + ex.Message);
                    }
                }
            }

            // After running the code, check the output file and compare its content to the input image to ensure data integrity.

        }
0

There are 0 best solutions below