Tag: c# graphics
c# reading Tiff using libtiff
by brian on Mar.20, 2008, under c#, c# coding GUI, graphics
| Here is the promised code for reading Tiffs. I make no claim that this code will read all TIFF files that would be quite the accomplishment indeed. Because of time constraints, I’m just going to cut this right out of the application I’m writing. As way of explanation the class ImageArray is basically an array of pixels wrapped around a class. A pixel here is a class that consists of r,g,b colors and a few other things. In my last post I had some of the libtiff header defined. I’m going to skip that here and just post the code. |
public static ImageArray LoadTiff(String Image_Path)
{
ImageArray arr = null;
unsafe
{
UInt32 w = 0;
UInt32 h = 0;
uint samples = 3;
uint bits = 8;
int i, j, ptr, lptr;
int tif = TIFFOpen(Image_Path, "r");
if (0 != tif)
{
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, ref w);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ref h);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, ref bits);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, ref samples);
arr = new ImageArray((int)w, (int)h);
// make sure we get all of the data.
if (bits == 16)
{
UInt32 size = w;
ushort* raster = (ushort *)_TIFFmalloc((uint)(size * sizeof(ushort) * samples));
// read in all of the lines
for (j = 0; j < h; j++)
{
TIFFReadScanline(tif, (byte *)raster, j, 0);
// copy line into data
for (i = 0, ptr=0; i < w; i++, ptr+=(int)samples)
{
if (samples == 3)
{
arr.Data[i + j * w].SetPixel(raster[i], raster[i + 1], raster[i + 2]);
}
else
{
ushort val = raster[i + samples - 1];
arr.Data[i + j * w].SetPixel(val,val,val);
}
}
}
_TIFFfree((byte *)raster);
}
else
{
// anything beside 16 bit
UInt32 size = h * w;
byte *raster = _TIFFmalloc( size );
int val = TIFFReadRGBAImage(tif, w, h, raster, 0);
// copy image data into a bitmap
if (val != 0)
{
for (j = 0, ptr = 0, lptr=0; j < h; j++)
{
for (i = 0; i < w; i++, ptr+=4, ptr++)
{
arr.Data[ptr].SetPixel((ushort)raster[lptr], (ushort)raster[lptr + 1], (ushort)raster[lptr + 2]);
} // for i
} // for j
} // if val
_TIFFfree(raster);
}
TIFFClose(tif);
} // if tif
} // unsafe
return arr;
}
