0

I'm using Libtiff.net to write tiled images into a tiff file. It works ok if Photometric is set to RBG, but if I use YCbCr (in order to reduce file size), I get the error "Application trasferred too few scanlines". Relevant pieces of code:

    private static Tiff CreateTiff()
    {
        var t = Tiff.Open(@"d:\test.tif", "w");
        const long TIFF_SIZE = 256;  
        t.SetField(TiffTag.IMAGEWIDTH, TIFF_SIZE);
        t.SetField(TiffTag.IMAGELENGTH, TIFF_SIZE);

        t.SetField(TiffTag.TILEWIDTH, TIFF_SIZE);
        t.SetField(TiffTag.TILELENGTH, TIFF_SIZE);

        t.SetField(TiffTag.BITSPERSAMPLE, 8);
        t.SetField(TiffTag.SAMPLESPERPIXEL, 3);

        t.SetField(TiffTag.COMPRESSION,  Compression.JPEG );
        t.SetField(TiffTag.JPEGQUALITY, 80L);

        t.SetField(TiffTag.PHOTOMETRIC, Photometric.YCBCR);

        t.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);

        return t;
    }
    private static void Go()
    {
        var tif = CreateTiff(true);
        var bmp = Image.FromFile(@"d:\tile.bmp") as Bitmap;
        var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        var size = bmp.Width;
        var bands = 3;
        var bytes = new byte[size * size * bands];
        var bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

        try
        {
                System.Runtime.InteropServices.Marshal.Copy(bmpdata.Scan0, bytes, 0, bytes.Length);
        }
        finally
        {
            bmp.UnlockBits(bmpdata);
            bmp.Dispose();
        }
        tif.WriteEncodedTile(0, bytes, bytes.Length);

        tif.Dispose();

        Console.ReadLine();
    }

This same code works if I use Photometric.RGB. Even if I write a stripped image (t.SetField(TiffTag.ROWSPERSTRIP, ROWS_PER_STRIP), tif.WriteEncodedStrip(count, bytes, bytes.Length)) using Photometric.YCbCr everything works just fine.

Why can't I use YCbCr with a tiled image? Thanks in advance.

Orphuio
  • 9
  • 2
  • You're not going to reduce file size using YCbCr over RGB unless you subsample the Cb and Cr components. – user3344003 Jun 05 '16 at 05:35
  • Thanks for your reply. The thing is, the tests I ran using stripped YCbCr have reduced file size greatly. I just need to do the same using **tiled** YCbCr. – Orphuio Jun 06 '16 at 06:28

1 Answers1

0

I finally found a workaround. I can set the tiff as RGB, encode the pixel data as YCbCr and then write it. The size of the output image is greatly reduced, as I desired, and then I can recover RGB values when I read the tiles. But it still isn't a perfect solution: any other software will recognize this tiff as RBG, so the colors are incorrect.

I thought of editing the photometric tag after writing the data, but every software I've tried either ignores the command or corrupts the file. How can I modify this tag without corrupting the image?

Orphuio
  • 9
  • 2