PointlessSpike
PointlessSpike

Reputation: 399

Example of converting JPG to TIFF using BitMiracle's LibTIFF.NET

I need to convert a series of JPGs into a TIFF, but I haven't been able to find an example that does it with even one JPG.

This is what ChatGPT gave me, but the resulting TIFF shows as corrupted.

using System;
using System.IO;
using BitMiracle.LibTiff.Classic;

namespace TiffConversionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string jpegPath = "input.jpg";
            string tiffPath = "output.tif";

            using (Tiff outputTiff = Tiff.Open(tiffPath, "w"))
            {
                using (FileStream jpegStream = File.OpenRead(jpegPath))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        // Copy the JPEG image data to a memory stream
                        jpegStream.CopyTo(memoryStream);
                        byte[] imageData = memoryStream.ToArray();

                        // Set the TIFF image width, height, and other required tags
                        outputTiff.SetField(TiffTag.IMAGEWIDTH, 640);
                        outputTiff.SetField(TiffTag.IMAGELENGTH, 480);
                        outputTiff.SetField(TiffTag.COMPRESSION, Compression.JPEG);
                        outputTiff.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
                        outputTiff.SetField(TiffTag.ROWSPERSTRIP, 8);

                        // Write the image data to the TIFF file
                        outputTiff.WriteRawStrip(0, imageData, imageData.Length);
                        outputTiff.WriteDirectory();
                    }
                }
            }

            Console.WriteLine("Conversion complete.");
        }
    }
}

I've reduced the complexity as much as I can to try to get a working example, with no joy.

For maximum points, provide an example of adding multiple JPGs to a multi-page TIFF. Failing that, an example of just a single page will be appreciated, or another library that can be used commercially for this purpose.

EDIT: To clarify, I need to do this in .Net Core, so the System.Drawing namespace is out.

Upvotes: 0

Views: 359

Answers (0)

Related Questions