Convert Tif indexed 8-bit colour to 32-bit colour

1.4k views Asked by At

I have an indexed Tiff image which I'm reading using LibTiff.Net to produce a bitmap image of a section of the large image. I believe the Tiff will have 256 colour entries which I want to convert to 256 32-bit pixel values to be used in the output bitmap.

int bitsPerSample = tif.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();
FieldValue[] colourIndex = tif.GetField(TiffTag.COLORMAP);
int[] palette = new int[256];
for( int i = 0; i < 256; i++ )
{
    short red = colourIndex[0].ToShortArray()[i];
    short green = colourIndex[1].ToShortArray()[i];
    short blue = colourIndex[2].ToShortArray()[i];

    palette[i] = ?
}

How do I convert the RGB shorts into a 32-bit pixel value?

2

There are 2 answers

0
Bobrovsky On

In a TIFF ColorMap, the number of values for each color is 2**BitsPerSample. Therefore, the ColorMap field for an 8-bit palette-color image would have 3 * 256 values.

The width of each value is 16 bits. 0 represents the minimum intensity, and 65535 represents the maximum intensity. Black is represented by 0,0,0, and white by 65535, 65535, 65535.

So, you probably should use following code:

ushort red = colourIndex[0].ToShortArray()[i];
ushort green = colourIndex[1].ToShortArray()[i];
ushort blue = colourIndex[2].ToShortArray()[i];

palette[i] = System.Drawing.Color.FromArgb(red / 255, green / 255, blue / 255).ToArgb();
5
arx On

Try System.Drawing.Color.FromArgb(red, green, blue).ToArgb().

However, this will only give the right results if LibTiff and Win32 both use the same byte ordering for their ARGB values. It also assumes your red, green, and blue values are in the range 0 to 255; you can scale them if not.