1

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?

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
JWood
  • 2,804
  • 2
  • 39
  • 64

2 Answers2

1

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.

arx
  • 16,686
  • 2
  • 44
  • 61
  • Excellent, thanks! That seems to be working. The colour values are 0...65536 so I've divided by 65535 and multiplied by 255 but they are very different to the expected colours. – JWood Jan 25 '12 at 17:08
  • You're using a `short` which runs from -32768 to 32767. I don't know if libtiff uses the whole range; either way your calculation isn't correct. – arx Jan 25 '12 at 17:31
  • Sorry, I should have mentioned that I'm using a ushort now. The calculation is correct. – JWood Jan 25 '12 at 17:38
  • In that case, the ARGB bytes are probably in the wrong order. The `Color` class uses `AARRGGBB` (i.e. A is the MSB, B is the LSB). You could try calling `FromArgb(blue, green, red, 255)` to reverse them. If that doesn't help, check the tiff/libtiff docs for the actual order. – arx Jan 25 '12 at 17:48
  • I just checked the docs; 24-bit RGB is more common in tiff. So you probably want `FromArgb(0, red, green, blue)` or `FromArgb(0, blue, green, red)`. – arx Jan 25 '12 at 17:53
0

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();
Bobrovsky
  • 13,789
  • 19
  • 80
  • 130