Manikanta Manikanta - 1 month ago 11
C# Question

Reading RGB values of a pixel with LibTiff - C#

I want to read RGB values of a pixel in C#, I tried using following code found here.

int[] raster = new int[height*width];
var b = tiffreader.ReadRGBAImage(width, height, raster);

for (int i = 0; i < width; ++i)
for (int j = 0; j < height; ++j)
{
int offset = (height - j - 1) * width + i;
color.R = Tiff.GetR(raster[offset]);
color.G = Tiff.GetG(raster[offset]);
color.B = Tiff.GetB(raster[offset]);
}


But I dint get What is this offset and why raster is in 1D when the Image is 2D. can some one help me in understanding the offset and raster thing in the above code.

Answer

A 2D byte array (and in this case, bitmap) is basically still a "normal" 1D array that allows access by two separate indices for convenience.

Example:

  0123456789
0 ##########
1 **********
2 XXXXXXXXXX
3 YYYYYYYYYY

#,*,X,Y denote the bytes in each entry

is actually (in memory)

##########**********XXXXXXXXXXYYYYYYYYYY

So that formula to map the indices is

int offset = i * width + j

with i being the row and j the column index.


In case of this TIFF image this is a little different because it is assumed that the origin is at the lower-left corner:

  0123456789
3 ####OO####
2 ##OO##OO##
1 ##OOOOOO##
0 ##OO##OO##

Thus,

int offset = (height - j - 1) * width + i;

is the formula that maps the two 2D indices to the 1D index of the raster array.

Comments