Reputation: 9
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.
Upvotes: 0
Views: 591
Reputation: 9
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?
Upvotes: 0